Write a function that calculates the Greatest Common Divisor of 2 numbers.
The Greatest Common Divisor (GCD) of two numbers is the largest positive integer that divides both the numbers without leaving any remainder.
Java
import java.util.*;
public class Solutions {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n1 = sc.nextInt();
int n2 = sc.nextInt();
while(n1 != n2) {
if(n1>n2) {
n1 = n1 - n2;
} else {
n2 = n2 - n1;
}
}
System.out.println("GCD is : "+ n2);
}
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n1 = sc.nextInt();
int n2 = sc.nextInt();
while(n1 != n2) {
if(n1>n2) {
n1 = n1 - n2;
} else {
n2 = n2 - n1;
}
}
System.out.println("GCD is : "+ n2);
}
}
Example no 2 in java:-
// java
public class Main {
public static int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static void main(String[] args) {
int a = 60, b = 48;
System.out.println("GCD of " + a + " and " + b + " is " + gcd(a, b));
}
}
Python:-
// python
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
a, b = 60, 48
print(f"GCD of {a} and {b} is {gcd(a, b)}")
C:-
// c
#include <stdio.h>
int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
int main() {
int a = 60, b = 48;
printf("GCD of %d and %d is %d\n", a, b, gcd(a, b));
return 0;
}
C++ :-
//cpp
#include <iostream>
using namespace std;
int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
int main() {
int a = 60, b = 48;
cout << "GCD of " << a << " and " << b << " is " << gcd(a, b) << endl;
return 0;
}
Other's blogs:-
>> Enter 3 numbers from the user & make a function to print their average in java, c++, python, java.
>> Package in Java| what is the case used for a package in java| creating packages in java
Comments
Post a Comment