Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added GCD.java #3094

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions Gcd/GCD.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
//java program to find the greatest comman divisor of 2 numbers
import java.util.Scanner;

public class GCD{
//recursive method which returns the gcd of two numbers m and n
public static int gcd(int m,int n){
//assuming m is greater than n
if(n>m){
//if n is greater than m, then swap
int temp=m;
m=n;
n=temp;
}
//if divisible, then n is the gcd
if(m%n==0)
return n;
//else, call the gcd for n and the remainder
else
return(gcd(n,m%n));
}

public static void main(String args[]){
//define Scanner object toread the input
Scanner sc=new Scanner(System.in);

//read the numbers
System.out.print("Enter Number 1 ");
int num1=sc.nextInt();
System.out.print("Enter Number 2 ");
int num2=sc.nextInt();

//call the function and display the results
System.out.println("Gcd of "+num1+", "+num2+" = "+gcd(num1, num2));
}
}


/*
* Output
* Enter number 1 14
* Enter number 2 63
* Gcd of 14, 63 = 7
*/