Calculating the number of representations of a number that is a sum of 3 squares
algorithm, c++
Solution
Here is a good starting point:
#include <cmath>
#include <iostream>
int count_sum_of_squares(int n)
{
int count=0;
// We only need to test numbers up to and including the square root of n.
// Also, we want to impose an ordering on [a, b, c] to consider
// combinations and NOT permutations.
for (int a=1; a<=int(sqrt(n)); ++a)
for (int b=1; b<=a; ++b)
for (int c=1; c<=b; ++c)
if (a*a+b*b+c*c==n) // If the squares of {a, b, c} add up to n
++count; // then this is a case that should be counted
return count;
}
int main()
{
std::cout << 3 << ': ' << count_sum_of_squares(3) << '\n';
std::cout << 14 << ': ' << count_sum_of_squares(14) << '\n';
std::cout << 27 << ': ' << count_sum_of_squares(27) << '\n';
std::cout << 866 << ': ' << count_sum_of_squares(866) << '\n';
}
Problem
I need to write a function head that returns the number of representations of a number as a sum of 3 positive squares. For example, the only representation of 3 as a sum of 3 squares is 3 = 1+1+1, so the function should return 1 if number = 3. If n is 27, the function should return 2 since 27 has two representations 27 = 25 + 1 +1 or 9+9+9. This is what I have tried: ``` #include <iostream> #include <cmath> using namespace std; int numRep(int num); int main() { int count = numRep(27); cout << count; return 0; } int numRep(int num) { int count = 0, sum = 0; int a =1, b=1, c=1; while(a*a <= num -2) { b = 1; while(b*b <= num -2) { c =1; while(c*c <= num -2) { sum = a*a + b*b + c*c; if (sum == num) count++; c++; } b++; } a++; } return count/3; } ``` But I am not getting correct output. Need some guidance... If there is a better method, do suggest..