HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyModerate

Simplify test for divisibility by all numbers 1…20

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
allnumberssimplifydivisibilityfortest

Problem

def divisible?(n)
  if n % 1 == 0 &&
    n % 2 == 0 &&
    n % 3 == 0 &&
    n % 4 == 0 &&
    n % 5 == 0 &&
    n % 6 == 0 &&
    n % 7 == 0 &&
    n % 8 == 0 &&
    n % 9 == 0 &&
    n % 10 == 0 &&
    n % 11 == 0 &&
    n % 12 == 0 &&
    n % 13 == 0 &&
    n % 14 == 0 &&
    n % 15 == 0 &&
    n % 16 == 0 &&
    n % 17 == 0 &&
    n % 18 == 0 &&
    n % 19 == 0 &&
    n % 20 == 0
    return true
  else 
    return false
  end
end

Solution

Ruby refactor: use Enumerable.all?:

def divisible?(n)
  (1..20).all? { |x| n % x == 0 }
end


Mathematical refactor:calculate the least common multiple of the integers in the range (Integer#lcm is available from Ruby 1.9):

def divisible?(n)
  n % (1..20).reduce(:lcm) == 0
end


This second snippet is, of course, more efficient once you pre-calculate (1..20).reduce(:lcm) only once and store it somewhere.

Code Snippets

def divisible?(n)
  (1..20).all? { |x| n % x == 0 }
end
def divisible?(n)
  n % (1..20).reduce(:lcm) == 0
end

Context

StackExchange Code Review Q#21238, answer score: 15

Revisions (0)

No revisions yet.