### java

#### list all pythagorean triplets in java

I need to find all pythagorean triples (a^2+b^2=c^2) with values of A and B less than 100. My codes don't give me the correct output. Could anyone tell me what went wrong with my codes and write the correct codes instead? public static void main(String[] args) { int sum = 0; for (int num1 = 1; num1 <= 100; num1++) { for (int num2 = 1; num2 < 100; num2++) { if (PerfectSquare(num1, num2, sum)) { System.out.println(num1 + " " + num2); } } } } public static boolean PerfectSquare(int number1, int number2, int sum) { int square1; int square2; double root; int sum1; number1 = (int) ((99 - 1 + 1) * Math.random() + 1); number2 = (int) ((99 - 1 + 1) * Math.random() + 1); square1 = (int) Math.pow(number1, 2.0); square2 = (int) Math.pow(number2, 2.0); sum = square1 + square2; root = Math.sqrt(sum); sum1 = (int) Math.pow(root, 2.0); if (!(sum == sum1)) { return false; } return true; }

You are overwriting your number1 and number2 parameters with random numbers: number1 = (int) ((99 - 1 + 1 ) * Math.random() + 1); number2 = (int) ((99 - 1 + 1 ) * Math.random() + 1); You may as well not be passing in any values at all into the method if you do this. Remove these lines. Also, you need to round your square root to an integer: root = (int) Math.sqrt(sum); since otherwise you will end up with the same number when you square it again. Other points not related to correctness: You can square integers without needing to cast by multiplying them with themselves: square1 = number1 * number1; This: if (! (sum==sum1) ) { is more easily written as if (sum != sum1) { Your sum method parameter is unnecessary. Declare it as a local variable. You don't need to loop over all pairs of num1 and num2, since if (num1, num2) are the opposite and adjacent sides of a Pythagorean triple, then (num2, num1) clearly are too (similarly if num1 and num2 aren't, then num2 and num1 aren't either). As such, you can check fewer combinations using: for (int num1 = 1; num1 <= 100 ; num1++) { for (int num2 =1; num2 <num1; num2++) {

### Related Links

Can't unset fullscreen mode in JavaFX

MySql not working on Amazon EC2

How to gracefully stop the executorservice with a stopfile approach

Why does this Calendar fail?

How to change a int number to the asci equivalent?

Circumventing ImageIO.write's slowness

Adding MouseListeners for JToolBar (events are consumed?)

“while” loop questions for Java

How can I get the (video) activities of a user with the YouTube API v3 in Java

Change endpoint reference on Remote object. Is it possible?

Unable to use method accessors on attributes in a session using JSTL

Java View Html Code as web-page

Slider hides sub-menus

Changing the Size of action Bar

redirecting to youtube to upload video available on jsp

Regular Expression breaking Due to line break character (\n)