Advertisement
Guest User

Untitled

a guest
Feb 10th, 2016
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class Euclid {
  4. public static Scanner Input = new Scanner(System.in);
  5.  
  6. public Answer greatestCommonDivisor(double one, double two) {
  7. double three = 0;
  8. int steps = 0;
  9. //with while we can actually assign and compare in one step which greatly simplifies things
  10. while ((three = one % two) != 0) {
  11. /* variable reassignment occurs here. While three does not equal 0 One is assigned the value of Two,
  12. * Two is assigned the value of Three then modulo occurs again to see if Three equals 0
  13. */
  14. one = two;
  15. two = three;
  16. steps++;
  17. }
  18. return new Answer(two, steps);
  19. }
  20.  
  21. public static void main(String[] args) {
  22. System.out.println("Welcome to this software, it calculates the greatest common divisor between two positive integers. What is your first number?");
  23. String Ans = Input.next();
  24. // One is assigned the value of input from the user. Same with two
  25. System.out.println("What is your second number?");
  26. String Ans2 = Input.next();
  27.  
  28. double one = Double.parseDouble(Ans);
  29. double two = Double.parseDouble(Ans2);
  30. Euclid seq = new Euclid();
  31. Answer answer = seq.greatestCommonDivisor(one, two);
  32.  
  33. System.out.println("The greatest common divisor of the two numbers is: " + answer.getAnswer());
  34. System.out.println("This was reached after this many steps : " + answer.getSteps());
  35. }
  36.  
  37. //create an inner class so we can return both Answer and amount of steps cleanly
  38. class Answer {
  39. private double answer=-1;
  40. private int steps=-1;
  41.  
  42. Answer(double answer, int steps) {
  43. this.answer = answer;
  44. this.steps = steps;
  45. }
  46.  
  47. public double getAnswer() {
  48. return answer;
  49. }
  50. public void setAnswer(double answer) {
  51. this.answer = answer;
  52. }
  53. public int getSteps() {
  54. return steps;
  55. }
  56. public void setSteps(int steps) {
  57. this.steps = steps;
  58. }
  59. }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement