Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,954 questions

51,896 answers

573 users

Find the minimum number of squares that sum of them equal to a given number in Java

1 Answer

0 votes
public class MyClass {
    public static boolean isPerfectSquare(int n) {
        double sqr = Math.sqrt(n);
 
        return sqr == Math.floor(sqr);
    }
    public static int findMinSquares(int n)
    {
        if (isPerfectSquare(n)) {
            return 1;
        }
 
        int squares = n;

        for (int i = 1; i * i < n; i++) {
            squares = Integer.min(squares, 1 + findMinSquares(n - i * i));
        }
 
        return squares;
    }
 
    public static void main(String args[]) {
        int n = 63; // 63 = 7*7(49) + 3*3(9) + 2*2(4) + 1*1(1) // 4 number of squares
        System.out.println("The minimum number of squares: " + findMinSquares(n));
        
        n = 23; // 23 = 3*3(9) + 3*3(9) + 2*2(4) + 1*1(1) // 4 number of squares
        System.out.println("The minimum number of squares: " + findMinSquares(n));
        
        n = 100; // 100 = 10*10(100) // 1 number of squares
        System.out.println("The minimum number of squares: " + findMinSquares(n));

    } 
}




/*
run:
 
The minimum number of squares: 4
The minimum number of squares: 4
The minimum number of squares: 1
 
*/

 



answered Nov 22, 2021 by avibootz
...