Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of two squares in C

Tags:

c

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?

like image 898
Thatdude1 Avatar asked Jan 28 '12 23:01

Thatdude1


People also ask

What is the formula for the sum of two squares?

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.

What is the sum of two perfect squares?

The sum of two perfect squares is a perfect square.

What is the example of sum of two squares?

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.


1 Answers

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;
}
like image 54
asaelr Avatar answered Oct 06 '22 19:10

asaelr