forked from chennakrishnans/JAVA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgcdlcm.java
93 lines (77 loc) · 2.01 KB
/
gcdlcm.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import java.util.Scanner;
import java.io.*;
public class GCD
{
static int gcd(int x, int y)
{
int r=0, a, b;
a = (x > y) ? x : y; // a is greater number
b = (x < y) ? x : y;
r = b;
while(a % b != 0)
{
r = a % b;
a = b;
b = r;
}
return r;
}
static int lcm(int x, int y)
{
int a;
a = (x > y) ? x : y; // a is greater number
while(true)
{
if(a % x == 0 && a % y == 0)
return a;
++a;
}
}
public static void main(String args[])
{
try
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter N value: ");
int N=sc.nextInt();
if(N==2)
{
System.out.println("Enter the two numbers: ");
int x = sc.nextInt();
int y = sc.nextInt();
System.out.println("The GCD of two numbers is: " + gcd(x, y));
System.out.println("The LCM of two numbers is: " + lcm(x, y));
}
if(N==3)
{
System.out.println("Enter the three numbers: ");
int x = sc.nextInt();
int y = sc.nextInt();
int z = sc.nextInt();
int i;
int a=Math.max(x,Math.max(y,z));
while(true)
{
if(a % x == 0 && a % y == 0 && a%z==0)
{
break;
}
else
++a;
}
System.out.println("LCM of "+x+", "+y+" and "+z+" is "+a);
int b=Math.min(x,Math.min(y,z));
for(i=b;i>=0;i--)
{
if((x%i==0) && (y%i==0) && (z%i==0))
break;
}
System.out.println("GCD of "+x+", "+y+" and "+z+" is "+i);
}
}
catch(Exception e)
{
System.out.println("Enter only numbers");
}
}
}