Daniel Maybach Daniel Maybach -4 years ago 66
Java Question

Program to find pythogorean triplet whose sum is 1000, cannot figure out why it doesn't work?

import java.util.*;
public class Euler9
{
public static void main (String[] args)
{
double a=3, b=4, c=5;
double pdt=0;
int i;
for(i=0;i<=500000;i++)
{
if ((a*a)+(b*b)==(c*c))
{
System.out.println("a = "+a+" b = "+b+" c = "+c+" is a pyth tripl.");
if ((a+b+c)==1000.0)
{
pdt=a*b*c;
break;
}
}
a++;
b++;
c++;
}
System.out.println(pdt);
}
}


Hey, I've been trying to do a few Euler problems for a class I'm taking, and this is my solution is Euler9, https://projecteuler.net/problem=9 but for some reason I cannot get this code to work. Regardless of the value I set i to it seems to end after a single iteration and I cannot figure out why for the life of me. Thanks for the help.

Answer Source

You can't increment all of them at once. You could do something like

for(int a = 0; a < 100; a++)
    for(int b = 0; b < 100; b++)
        for(int c = 0; c < 100; c++)
           if(a^2 + b^2 == c^2)
              ...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download