programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# help me to solve the program

Greenhorn
Posts: 7
Generate all 5 digit number pairs (a, b) which satisfies the following condition
1. a^2 + b^2 = c^2 (when you square the first number and add it to the square of second number, you should get an another perfect square)

2. Once you have generated a & b, you should not generate b,a

i wrote the program that satifies first condition but i don't know how to solve the second condition.please help me to solve that...

class demo1
{
public static void main(String args[])
{

for (double a=1;a<10000;a++)
{
for(double b=1;b<10000;b++)
{
double c=Math.pow(a,2)+Math.pow(b,2);
for(double k=1;k<10000;k++)
{
if(c==(k*k))
{

System.out.print(a);
System.out.print("\t" +b);
System.out.println("\t"+c);
}

}

}
}

}
}

Rancher
Posts: 3742
16
Originally posted by hershelll gibbs:
Generate all 5 digit number pairs

I'm not sure you have done the first part. The way I read it the question is asking for numbers between 10000 and 99999 inclusive.

Marshal
Posts: 56600
172
These are Pythagorean triplets. They are the sides of right-angled triangles which are all integral. You don't want to try a loop at all, but solve the equations.
Try with b, c = b + 1, then work out a. Imagine they are the sides of a triangle where a is the short side, b the opposite side and c the hypotenuse.

(x + y)^2 = x^2 + 2xy + y^2, as I learned when I did algebra at school, so
(a + 1)^2 = a^2 + 2a + 1, so
c^2 = (b + 1)^2, so
a^2 + b^2 = (b + 1)^2, so
a^2 + b^2 = b^2 + 2b + 1, so
a^2 = 2b + 1.

You are looking for whole numbers which fit the equation a^2 = 2n + 1, so start from n = 0 and count up one at a time until you reach b >= 100000.

If you think Joanne Neal is correct about starting from 10000 then start from n = 5000 and finish when b passes 99999.

Campbell Ritchie
Marshal
Posts: 56600
172
And don't use Math.pow to square int numbers. Use i * i.