Problem:
Given two positive non-zero integers n and m design an algorithm and implement their greatest common divisor.
Solution:
package com.myprograms;
import java.util.Scanner;
public class GCDOfTwoNumbers {
int smallNumber;
int largerNumber;
int result;
int input1;
int input2;
public static void main(String[] args) {
GCDOfTwoNumbers gcdOfTwoNumbers = new GCDOfTwoNumbers();
gcdOfTwoNumbers.getTheNumbers();
gcdOfTwoNumbers.findGCD();
gcdOfTwoNumbers.printTheResult();
}
public void getTheNumbers(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter first number");
input1 = scanner.nextInt();
System.out.println("enter second number");
input2 = scanner.nextInt();
if(input1>input2){
largerNumber = input1;
smallNumber = input2;
}
else {
largerNumber = input2;
smallNumber = input1;
}
scanner.close();
}
public void findGCD(){
int reminder = largerNumber % smallNumber;
while(reminder != 0){
largerNumber = smallNumber;
smallNumber = reminder;
reminder = largerNumber % smallNumber;
}
result = smallNumber;
}
public void printTheResult(){
System.out.println("the Greatest Common Divisor of " + input1 + " and " + input2 + " is: " + result);
}
}
Output:
enter first number
18
enter second number
24
the Greatest Common Divisor of 18 and24 is: 6
Given two positive non-zero integers n and m design an algorithm and implement their greatest common divisor.
Solution:
package com.myprograms;
import java.util.Scanner;
public class GCDOfTwoNumbers {
int smallNumber;
int largerNumber;
int result;
int input1;
int input2;
public static void main(String[] args) {
GCDOfTwoNumbers gcdOfTwoNumbers = new GCDOfTwoNumbers();
gcdOfTwoNumbers.getTheNumbers();
gcdOfTwoNumbers.findGCD();
gcdOfTwoNumbers.printTheResult();
}
public void getTheNumbers(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter first number");
input1 = scanner.nextInt();
System.out.println("enter second number");
input2 = scanner.nextInt();
if(input1>input2){
largerNumber = input1;
smallNumber = input2;
}
else {
largerNumber = input2;
smallNumber = input1;
}
scanner.close();
}
public void findGCD(){
int reminder = largerNumber % smallNumber;
while(reminder != 0){
largerNumber = smallNumber;
smallNumber = reminder;
reminder = largerNumber % smallNumber;
}
result = smallNumber;
}
public void printTheResult(){
System.out.println("the Greatest Common Divisor of " + input1 + " and " + input2 + " is: " + result);
}
}
enter first number
18
enter second number
24
the Greatest Common Divisor of 18 and24 is: 6
enter first number
18
enter second number
30
the Greatest Common Divisor of 18 and 30 is: 6
enter first number
54
enter second number
24
the Greatest Common Divisor of 54 and 24 is: 6
No comments:
Post a Comment