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,955 questions

51,897 answers

573 users

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

1 Answer

0 votes
#include <iostream>
#include <cmath>

bool isPerfectSquare(int n) {
    long double sqr = sqrt(n);
 
    return sqr == floor(sqr);
}
 
int findMinSquares(int n) {
    if (isPerfectSquare(n)) {
        return 1;
    }
 
    int result = n;
 
    for (int i = 1; i * i < n; i++) {
        result = std::min(result, 1 + findMinSquares(n - i*i));
    }
 
    return result;
}
 
int main()
{
    int n = 63; // 63 = 7*7(49) + 3*3(9) + 2*2(4) + 1*1(1) // 4 number of squares
    std::cout << "The minimum number of squares: " << findMinSquares(n) << "\n";
         
    n = 23; // 23 = 3*3(9) + 3*3(9) + 2*2(4) + 1*1(1) // 4 number of squares
    std::cout << "The minimum number of squares: " << findMinSquares(n) << "\n";
         
    n = 100; // 100 = 10*10(100) // 1 number of squares
    std::cout << "The minimum number of squares: " << findMinSquares(n) << "\n";
 
    return 0;
}



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

 



answered Nov 23, 2021 by avibootz
...