Home > Software design >  Ruby- prime number unique and duplicates
Ruby- prime number unique and duplicates

Time:03-14

I'm just learning Ruby :) and Im trying to create a simple prime-number program where all the primes of a number are printed.

I'm getting errors where the prime and nonprime numbers are mixed up (ie: input of 9 will get you all nonprimes).

I also want my program to print out a list of factors (including duplicates), as well as the unique set of factors in ascending order. Any tips on how I should code this?

I'm sorry for such a beginner question - I'm struggling alot and need some help :)

puts "Enter a number please "
num = gets.chomp.to_i

i = 2
number = 2

while i < num
  if number % i == 0
    prime = false
  end
    i  = 1
  end
  if prime == true
    puts "#{number} is prime"
  else
    puts "#{number} is not prime"
  end
  number  = 1
end

CodePudding user response:

while i < num
  if number % i == 0
    prime = false
  end
    i  = 1
  end
  # ...

It looks like that first end is meant to be an else.

It's easier to catch these things when you simplify your code, e.g. this method reduces to this (although there are other issues with it):

i = 2
number = 2

while i < num
  (number % i).zero? ? prime = false : i  = 1
  puts "#{number} is #{'not ' unless prime}prime"
  number  = 1
end

CodePudding user response:

End error is because of else

while i < num
  if number % i == 0
    prime = false
  else
    i  = 1
  end

if you have a short If - neater is writing it like:

if-condition ? 1 : 0 

and in your case while is.. not the nicest choice - you should use range

(1...3).map{|x|  puts(x) }

{} - allows multiline(with do end end)

this prints [1,2]

(1..3).map{|x| x*2 }

would be [2,4,9]

This should be enough hints of how to play around with your code without ruining the process.

  • Related