Write a C++ program to find the number of perfect square (e.g. 1, 4, 9, 16, ...) numbers which represent a sum of a given number

  • برمجة سي بلس بلس
  • برمجة

Write a C++ program to find the number of perfect square (e.g. 1, 4, 9, 16, ...) numbers which represent a sum of a given number

Sample Input: n = 5
Number of perfect square whose sum equal to 5 = 2
Sample Input: n = 7
Number of perfect square whose sum equal to 7 = 4

Sample Output:

Number of perfect square whose sum equal to 5 = 2

Number of perfect square whose sum equal to 7 = 4

Number of perfect square whose sum equal to 12 = 3

الأجوبة

#include <iostream>
#include <vector>

using namespace std;

int numSquares(int n) {
        
        vector<int> table(n + 1, 0);

        for(auto i = 1; i <= n; ++i)
        {
            int value = INT_MAX;
            for(auto j = 1; j * j <= i; ++j)
            {
                value = min(value, table[i - j * j] + 1);
            }

            table[i] = value;
        }

        return table[n];
    }

int main() 
{
    int n = 5;  // (4 + 1)
    cout << "\nNumber of perfect square whose sum equal to " << n << " = " << numSquares(n) << endl;
	n = 7;  // (4 + 1 + 1 + 1)
    cout << "\nNumber of perfect square whose sum equal to " << n << " = " << numSquares(n) << endl;	   	  	  	  	        	        
    n = 12;  // (4 + 4 + 4)
    cout << "\nNumber of perfect square whose sum equal to " << n << " = " << numSquares(n) << endl;
	return 0;
    
}
هل كان المحتوى مفيد؟

تبحث عن مدرس اونلاين؟

محتاج مساعدة باختيار المدرس الافضل؟ تواصل مع فريقنا الان لمساعدتك بتأمين افضل مدرس
ماهو التخصص الذي تبحث عنه؟
اكتب هنا...