PaulM
PaulM

Reputation: 1

Checking if an integer will be returned

As part of a Ruby training exercise I'm trying to find out how many divisors the number 'n' has. I plan to write something like:

x = 1,  
while n > x do ___,  
n/x,   
if n/x = integer, 
puts x,   
x = x+1.

Obviously, that won't work. I suppose what I'm asking is how to properly write "if n/x is an integer, puts x."

Thanks for any help.

Upvotes: 0

Views: 61

Answers (2)

iGian
iGian

Reputation: 11193

You can take a look at the Ruby standard library Prime class which defines the method Prime#prime_division.

So, given a number n = 3780, you can get its prime factors and exponents:

require 'prime'

n = 2**2 * 3**3 * 5 * 7 #=> 3780
Prime.prime_division(n) #=> [[2, 2], [3, 3], [5, 1], [7, 1]]

You can then map the exponent, add one to each of the mapped elements and multiply the elements each other to get the number of divisors, including 1 and n itself:

Prime.prime_division(n).map{|n| n.last + 1}.inject(:*)
#=> 48

Here you can find how it works: https://www.math.upenn.edu/~deturck/m170/wk2/numdivisors.html

Upvotes: 1

Stefan
Stefan

Reputation: 114178

how to properly write "if n/x is an integer, puts x."

You'd typically use the modulo operation (% in Ruby) and check if it returns 0:

6 % 1 #=> 0
6 % 2 #=> 0
6 % 3 #=> 0
6 % 4 #=> 2
6 % 5 #=> 1

Your pseudo code transformed into Ruby:

n = 6
x = 1
while n > x
  if n % x == 0
    puts x
  end
  x = x + 1
end

Or more idiomatic and slightly optimized: (only traversing up to n/2)

n = 6
1.upto(n/2).select { |i| n % i == 0 }
#=> [1, 2, 3]

Note that this returns an array. Put a puts in front of it in order to print its elements.

Upvotes: 1

Related Questions