Skip to content

Instantly share code, notes, and snippets.

@benchristel
Created October 31, 2019 15:53
Show Gist options
  • Save benchristel/5a171cb323c114ec250aa594f62d058f to your computer and use it in GitHub Desktop.
Save benchristel/5a171cb323c114ec250aa594f62d058f to your computer and use it in GitHub Desktop.
Verse GCF
define({
'test greatest common factor of primes is 1'() {
assert(gcf(1, 3), is, 1)
assert(gcf(7, 3), is, 1)
assert(gcf(7, 57), is, 1)
},
'test gcf of 0 and 0 is NaN'() {
assert(gcf(0, 0), isNaN)
},
'test gcf of 0 and x is x'() {
assert(gcf(0, 1), is, 1)
assert(gcf(0, 22), is, 22)
assert(gcf(23, 0), is, 23)
},
'test gcf of x and x is x'() {
assert(gcf(3, 3), is, 3)
assert(gcf(129, 129), is, 129)
},
'test greatest common factor does not care about order'() {
assert(gcf(3, 1), is, 1)
assert(gcf(3, 7), is, 1)
},
'test gcf when one number is a factor of the other'() {
assert(gcf(3, 51), is, 3)
},
'test gcf when neither number is a factor of the other'() {
assert(gcf(98, 22), is, 2)
assert(gcf(12, 9), is, 3)
assert(gcf(12, 8), is, 4)
assert(gcf(42, 18), is, 6)
assert(gcf(123, 45), is, 3)
assert(gcf(96, 20), is, 4)
},
gcf(a, b) {
if (a === 0 && b === 0) return NaN
if (a === 0) return b
if (b === 0) return a
let lesser = Math.min(a, b)
let greater = Math.max(a, b)
let remainder = greater % lesser
switch (remainder) {
case 0:
// `lesser` is a factor of `greater`.
// Since the GCF cannot be > `lesser`, it is `lesser`
return lesser
default:
// `lesser` is not a factor of `greater`.
// The GCF must be a factor of all of `lesser`, `greater`,
// and `remainder`. Since `remainder` < `lesser`, we can
// reduce the problem to finding the GCF of `remainder`
// and `lesser`.
return gcf(remainder, lesser)
}
},
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment