I have managed to get the sum of two squares, but it still doesnt work if for example 10: i need 9 and 1 ... My idea is to seacrch all the previous squares and find out how many will add up to the input, (max = 4) ... but im get stuck when duplicates occur and when i need to add 3 things... For 4 things I'm thinking of just adding an else statement. Any ideas/suggestions of how i can improve my algorithm?
a2 + b2 formula is known as the sum of squares formula in algebra and it is read as a square plus b square. Its expansion is expressed as a2 + b2 = (a + b)2 - 2ab.
The sum of two perfect squares is a perfect square.
If integers N and M can each be written as the sum of two squares, so can their product! Example: since 2=12+12 and 34=32+52, their product 68 should be expressible as the sum of two squares. In fact, 68=82+22.
Assume that you aren't supposed to use complex algorithm, I suggest you to loop through all the options, and check if the sum of squares make the number you need. While computing, you may also want to save the numbers in a global array, to simplify getsquare
Edit: since it's a nice problem, I wrote some code. (WARNING: I didn't check it)
int root[4];
int isqrt(int i) {return (int)floor(sqrt((double)i));}
// check if n is sum of s squares. assume s<=4
int canbesum(int s,int n) {
if (s==0) return n==0;
int i;
for (i=isqrt(n);i;i--)
if (canbesum(s-1,n-i*i)) {
root[s-1]=i;
return 1;
}
return 0;
}
int sumofsquares (int x) {
int i;
for (i=0;i<=4;i++) if (canbesum(i,x)) return i;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With