1

I am trying to create a program that prompts a user to input a number and then checks if its a prime number. I am also trying to get it to display the factors if it isn't a prime number.

I managed to create the first part of the program, but I am struggling with the last part.

def prime(n)
 is_prime = true
  for i in 2..n-1
   if n % i == 0
   is_prime = false
end
 end

if is_prime
 puts "#{n} is a prime number"
else
 puts "#{n} is not a prime number =>" 

end
 end


prime(n)

At this step:

puts "#{n} is not a prime number =>" 

I want to incorporate the displaying of factors, let's say the number is 8

8 is not a prime number => 1, 2, 4, 8

Any help or advice would be greatly appreciated!

Vroryn
  • 125
  • 6

1 Answers1

1

Try this code:

def factors(n)
  (1..n/2).select{|e| (n%e).zero?}.push(n)
end

factors(8) => [1,2,4,8]

and your last step will look as:

puts "#{n} is not a prime number =>#{factors(n).join(',')}" 

By the way: for check if number is prime, advice to use Sieve of Eratosthenes.

Community
  • 1
  • 1
Dmitry Cat
  • 475
  • 3
  • 11
  • 1
    You can speed up your factor-finding code by 100%. You only need to check the first half (`c / 2`) numbers. The second half will never result in a factor (except for `c` itself) – Sergio Tulentsev Mar 03 '17 at 08:23
  • 1
    Also, use `select` instead of `map + compact`. Will look much cleaner. – Sergio Tulentsev Mar 03 '17 at 08:26
  • Hi, that worked, thank you! But would you mind explaining what select, join and .zero? do? I am relatively new to ruby :/ – Vroryn Mar 03 '17 at 08:34
  • 1
    Hey, no prob: 1. (1..n/2) generates Range class from 1 to n/2 2. select does select from Range elements, where n%e == 0 zero? method returns true, if number == 0; select method returns array 3. push(n) adds to array element(n) – Dmitry Cat Mar 03 '17 at 08:39