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
- برمجة سي بلس بلس
- برمجة
- 2021-05-13
- MarwaMohammed
الأجوبة
#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;
}
أسئلة مشابهة
القوائم الدراسية التي ينتمي لها السؤال