1
\$\begingroup\$

I've already reduced it and have tried making the main code is_divisible=, followed directly by the (2...).each... code, but that didn't work.

Any suggestions on reducing the size of this code? I have tests for other methods that use the code (so I know if changes are working) but not unit tests for this method yet.

  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
\$\endgroup\$

2 Answers 2

7
\$\begingroup\$
  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
\$\endgroup\$
0
2
\$\begingroup\$

Unless I'm missing something, I think this is equivalent to you your version.

require 'prime'

def self.divisible?(n)
  !n.prime?
end

If you don't want a dependency on the standard library then Jan Dvorak has a better solution.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.