def self.divisible?(n)
is_divisible= false
(2...n).each do |divisor|
division=n/divisor
if n== divisor*division
is_divisible= true
end
end
is_divisible
end
since you're returning a flag just after computing it, you could just return true
instead of setting the flag, and return false
if you get to the end. This saves you one line. But, Ruby arrays have the any?
and all?
predicates. Let's rewrite your code to use any?
. This reduces the if
condition to only its head. I hope you don't mind if I normalise the whitespace along the way:
def self.divisible?(n)
(2...n).any? do |divisor|
division = n / divisor
n == divisor * division
end
end
we could inline division
(n == (n / division) * division
), but let's use the modulo operator instead. Note that unlike your algorithm, modulo even works for floats and even rationals.
def self.divisible? (n)
(2...n).any? do |divisor|
n % divisor == 0
end
end
If you don't mind, I'll reduce the line count further by performing a style change here.
def self.divisible? (n)
(2...n).any? {|divisor| n % divisor == 0}
end
I don't think you can get shorter than that.
but if your intention is to generate a list of primes, you should only test divisibility by said primes.
def primes_until n
list = []
(2..n).each do |x|
list << x unless list.any? {|d| x % d == 0}
end
list
end
Written as a reduce
:
def primes_until n
(2..n).reduce([]) do |list, x|
list << x unless list.any? {|d| x % d == 0}
list
end
end