Welcome to collectivesolver - Programming & Software Q&A with Examples. A website you can trust. All programs tested and work.

Contact: aviboots(AT)netvision.net.il


Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Survey Junkie is the #1 place online for your audience to earn rewards for their opinion.

100%
Managed VPS Hosting
Affordable. Secure. Your Own Virtual Private Hosting. Faster than AWS and Rackspace

Bonsai Boy of New York Bonsai Trees and Accessories
Liquid Web - Highest Level of Performance and Security with Managed Dedicated Servers

Disclosure We are a professional Programming & Software Q&A website, that receives compensation from some of the links whose we show you with Information. It means that my content may contain affiliate links.

20,687 questions

27,329 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 by avibootz
...