File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
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)
You can’t perform that action at this time.
0 commit comments