Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class Euclid {
- public static Scanner Input = new Scanner(System.in);
- public Answer greatestCommonDivisor(double one, double two) {
- double three = 0;
- int steps = 0;
- //with while we can actually assign and compare in one step which greatly simplifies things
- while ((three = one % two) != 0) {
- /* variable reassignment occurs here. While three does not equal 0 One is assigned the value of Two,
- * Two is assigned the value of Three then modulo occurs again to see if Three equals 0
- */
- one = two;
- two = three;
- steps++;
- }
- return new Answer(two, steps);
- }
- public static void main(String[] args) {
- System.out.println("Welcome to this software, it calculates the greatest common divisor between two positive integers. What is your first number?");
- String Ans = Input.next();
- // One is assigned the value of input from the user. Same with two
- System.out.println("What is your second number?");
- String Ans2 = Input.next();
- double one = Double.parseDouble(Ans);
- double two = Double.parseDouble(Ans2);
- Euclid seq = new Euclid();
- Answer answer = seq.greatestCommonDivisor(one, two);
- System.out.println("The greatest common divisor of the two numbers is: " + answer.getAnswer());
- System.out.println("This was reached after this many steps : " + answer.getSteps());
- }
- //create an inner class so we can return both Answer and amount of steps cleanly
- class Answer {
- private double answer=-1;
- private int steps=-1;
- Answer(double answer, int steps) {
- this.answer = answer;
- this.steps = steps;
- }
- public double getAnswer() {
- return answer;
- }
- public void setAnswer(double answer) {
- this.answer = answer;
- }
- public int getSteps() {
- return steps;
- }
- public void setSteps(int steps) {
- this.steps = steps;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement