Greatest Common Factor

Write a method that takes in two numbers. Return the greatest integer that evenly divides both numbers. You may wish to use the % modulo operation.

Solution #1:

Screen Shot 2016-08-23 at 1.59.51 PM

Provided solution:

Screen Shot 2016-08-23 at 2.00.13 PM

Still not sure why we have to start i at the smaller number in either solution.

Second time solving this, I had a much easier time  diving into the problem after outlining my thoughts first.

Thought process:

(number1, number 2) == biggest_common_factor

Example: (16, 24) == 8

Determine the limit of which you’ll run the while loop, which in this case is the smaller of the two numbers given. (Because we’re trying to find the biggest common number, and it can’t be anything bigger than either numbers).

upper limit = smaller number

Find all the common factors for both numbers.

number1 % common_factor == 0
number2 % common_factor == 0

16: 2, 4, 8, 16
24: 2, 4, 3, 6, 8, 12, 24

Compare all the common factors one by one and return the biggest one. 

=> 8


NOTE: ‘i > biggest_common_factor’ is not necessary because it’s implied that ‘i’ will always be bigger since we’re incrementing.


Greatest Common Factor

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s