Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Decompose an integer into sum of 2 squares

807601Jan 31 2008 — edited Feb 1 2008
Hi all, I need to see how many ways an integer can be written as a sum of 2 squares.
EX:
On input 1, return 1 since 1 = 0*0 + 1*1
On input 5, return 1 since 5 = 1*1 + 2*2
On input 7, return 0 since 7 cannot be written as the sum of two squares.
On input 65, return 2 since 65 = 1*1 + 8*8 = 4*4 + 7*7
On input 85, return 2 since 85 = 2*2 + 9*9 = 6*6 + 7*7
Here's the code I have written, can somebody correct this code, this does not seem to work.
public class isSumOf
{
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
int n;
System.out.print("Enter number:");
n=input.nextInt();

System.out.println(isSumOfTwoSquares(n));

}


public static int isSumOfTwoSquares( int n )
{
int count=0;
for( int i = 1 ; 2 * i * i <= n ; i++ )
{
double d = Math.sqrt( n - i * i ) ;
if( d == (int) d)
count++;
return (count);

}

return 0;
}
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Feb 29 2008
Added on Jan 31 2008
10 comments
888 views