Facebook Hacker Cup 2012 starts later today, so I am warming up trying to solve last year’s problems. Here’s the first one:
A double-square number is an integer X which can be expressed as the sum of two perfect squares. For example, 10 is a double-square because 10 = 32 + 12. Your task in this problem is, given X, determine the number of ways in which it can be written as the sum of two squares. For example, 10 can only be written as 32 + 12 (we don’t count 12 + 32 as being different). On the other hand, 25 can be written as 52 + 02 or as 42 + 32.
Input
You should first read an integer N, the number of test cases. The next N lines will contain N values of X.
Constraints
0 ≤ X ≤ 2147483647
1 ≤ N ≤ 100
Output
For each value of X, you should output the number of ways to write X as the sum of two squares.
Solution: My first approach was a simple brute force algorithm trying all the different sums of squares:
#include <iostream>
#include <cmath>
using namespace std;
int isPerfectSquare(int n){
int x = int(sqrt(n));
if (x*x==n)
return 1;
return 0;
}
int findWays(int x){
int result;
int count = 0;
if (isPerfectSquare(x))
count++;
for (int i=1;i<x;i++){
for (int j=1;j<x;j++){
if (i*i>x)
goto end;
if (i>j)
continue;
result = (i*i) + (j*j);
if (result==x)
count++;
else if(result>x)
break;
}
}
end:
return count;
}
int main(){
int n,x;
cin >> n;
for (int i=0;i<n;i++){
cin >> x;
cout << findWays(x) << endl;
}
return 0;
}
It didn’t solve the input file within 6 minutes, though, so I needed something faster. Thinking a bit I realized that I only needed to go through the numbers once, checking whether or not their square with some other perfect square would add up to input number. This approach worked pretty fast:
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <cstdio>
using namespace std;
int isPerfectSquare(int n){
int x = int(sqrt(n));
if (x*x==n)
return 1;
return 0;
}
int findWays(int x){
int result;
int count = 0;
if (isPerfectSquare(x)){
count++;
}
for (int i=1;i<sqrt(x);i++){
result = i*i;
if (result<x-result){
if (isPerfectSquare(x-result)){
count++;
}
}
}
return count;
}
int main(){
int n,x;
cin >> n;
for (int i=0;i<n;i++){
cin >> x;
cout << "Case #" << i+1 << ": " << findWays(x);
if (i<n-1)
cout << endl;
}
return 0;
}