Problem:
Design and implement a gcd algorithm that does not use either division or modulo functions.
Solution:
package com.myprograms;
import java.util.Scanner;
public class GCDOfTwoNumbersWithoutDivision {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("enter first number");
int n1 = scanner.nextInt();
System.out.println("enter second number");
int n2 = scanner.nextInt();
while(n1 != n2)
{
if(n1 > n2)
n1 = n1-n2;
else
n2 = n2-n1;
}
System.out.print("the Greatest Common Divisor of given number is " + n1);
scanner.close();
}
}
Output:
enter first number
30
enter second number
18
the Greatest Common Divisor of given number is 6
Design and implement a gcd algorithm that does not use either division or modulo functions.
Solution:
package com.myprograms;
import java.util.Scanner;
public class GCDOfTwoNumbersWithoutDivision {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("enter first number");
int n1 = scanner.nextInt();
System.out.println("enter second number");
int n2 = scanner.nextInt();
while(n1 != n2)
{
if(n1 > n2)
n1 = n1-n2;
else
n2 = n2-n1;
}
System.out.print("the Greatest Common Divisor of given number is " + n1);
scanner.close();
}
}
Output:
enter first number
30
enter second number
18
the Greatest Common Divisor of given number is 6
No comments:
Post a Comment