-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathGCD
More file actions
71 lines (56 loc) · 2.1 KB
/
GCD
File metadata and controls
71 lines (56 loc) · 2.1 KB
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
/* Online Java Compiler and Editor */
import java.util.*;
public class HelloWorld{
public static void main(String []args){
// Creating the instance of Scanner class here
Scanner sc = new Scanner(System.in);
System.out.println("Please Enter the first number");
// Taking input integer from user and stroing into the first varibale
int first = sc.nextInt();
System.out.println("Please Enter the Second number");
// Taking input integer from user and stroing into the second variable
int second = sc.nextInt();
// We need to find gcd that we know any number which is highest divisor of both number is gcd
// divisor is which gives you the remainder when you divide some number with it
// checking remainder you can use modular operator
// I have one number n and want to divide that number with p and want check whether n is divisble by p or not if divisible p is divisor of n if( n%p == 0) it means p is the divisor of n
// first check the number and store somwhere
int min = first>second ? second: first;
// if(first>second) {
// min = second
// } else {
// min= first
// }
int max_divisor =0;
for(int i=1;i<=min;i++) {
if(first%i==0 && second%i==0) {
max_divisor=i;
}
}
System.out.println("GCD OF TWO NUMBER IS: "+ max_divisor );
// lest discuss time complexity program
// O(min(first, second))
}
}
// Second Approach
/* Online Java Compiler and Editor */ this code will not work in ediotr this is just simple pseudo code
public class HelloWorld{
public static void main(String []args){
// Another approach
int n= 12;
int m =24;
while(n!m){
if(n>m) {
n= n-m;
// n-=m
} else {
m= m-n;
// m-=n
}
}
Syetm.out.println(n);
}
// recursive gcd
public static void gcd(int a, int b){
return (b == 0) ? a : gcd(b, a % b);
}