Skip to content

Commit 0e93c8c

Browse files
Add files via upload
1 parent 1540237 commit 0e93c8c

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

Math/Pythagorean.java

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// Java program to generate pythagorean triplets smaller than a given limit
2+
3+
import java.util.*;
4+
5+
public class Pythagorean {
6+
7+
// Function to generate pythagorean triplets smaller than limit
8+
static void pythagoreanTriplets(int limit)
9+
{
10+
11+
// triplet: a^2 + b^2 = c^2
12+
int a, b, c = 0;
13+
14+
// loop from 2 to max_limit
15+
int m = 2;
16+
17+
// Limiting c would limit
18+
// all a, b and c
19+
while (c < limit) {
20+
21+
// now loop on j from 1 to i-1
22+
for (int n = 1; n < m; ++n) {
23+
// Evaluate and print
24+
// triplets using
25+
// the relation between
26+
// a, b and c
27+
a = m * m - n * n;
28+
b = 2 * m * n;
29+
c = m * m + n * n;
30+
31+
if (c > limit)
32+
break;
33+
34+
System.out.println(a + " " + b + " " + c);
35+
}
36+
m++;
37+
}
38+
}
39+
public static void main(String []args)
40+
{
41+
int limit = 20;
42+
pythagoreanTriplets(limit);
43+
}
44+
}
45+
//Time complexity of this approach is O(n) where n is number of triplets printed
46+
// for a given limit (We iterate for m and n only and every iteration prints a triplet)

0 commit comments

Comments
 (0)