posted Oct 11, 2013, 8:43 AM by Samuel Konstantinovich   [ updated Oct 11, 2013, 11:48 AM ]

Finding the GCD can be done in many ways. You will implement two ways:

1. A super naive way is just subtract the larger from the smaller over and over until:

-The numbers become the same , that is the GCD


21 6 

15 6

9 6

3 6

3 3 -> answer 3.

There are better ways such as Euclids algorithm:    euclids(A , B ) 

-> when B is 0, gcd is A.

-> otherwise A gets the value of the old B, B gets the value of the old A mod old B.


21 6

6 3

3 0 -> answer 3

LAB/HW5: Place HW5.java in the HW5 folder on your dropbox

  1. public int gcd(int a, int b) - this will find the greatest common divisor using the brute force method we discussed in class.
  2. public int gcd2(int a, int b) - this will return the gcd but this time using Euclid’s algorithm, as discussed in class. (Write it using a while loop)
  3. Write gcd2 again recursively gcd2r(a,b)  )
  4. Test gcd and gcd2 on a couple of large primes to see if there’s a speed difference. This is a large prime  188748146801L (notice the L, this is a long, not a normal int...) e.g.   long x =  188748146801L;
  5. Write isPrime(int n) which will return true if n represents a prime number and false otherwise.