Advertisement
Guest User

Untitled

a guest
Jan 18th, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. # Write a method that takes in an integer (greater than one) and
  2. # returns true if it is prime; otherwise return false.
  3. #
  4. # You may want to use the `%` modulo operation. `5 % 2` returns the
  5. # remainder when dividing 5 by 2; therefore, `5 % 2 == 1`. In the case
  6. # of `6 % 2`, since 2 evenly divides 6 with no remainder, `6 % 2 == 0`.
  7. # More generally, if `m` and `n` are integers, `m % n == 0` if and only
  8. # if `n` divides `m` evenly.
  9. #
  10. # You would not be expected to already know about modulo for the
  11. # challenge.
  12. #
  13. # Difficulty: medium.
  14.  
  15. def is_prime?(number)
  16. if number <= 1
  17. # only numbers > 1 can be prime.
  18. return false
  19. end
  20.  
  21. idx = 2
  22. while idx < number
  23. if (number % idx) == 0
  24. return false
  25. end
  26.  
  27. idx += 1
  28. end
  29.  
  30. return true
  31. end
  32.  
  33. # These are tests to check that your code is working. After writing
  34. # your solution, they should all print true.
  35.  
  36. puts("\nTests for #is_prime?")
  37. puts("===============================================")
  38. puts('is_prime?(2) == true: ' + (is_prime?(2) == true).to_s)
  39. puts('is_prime?(3) == true: ' + (is_prime?(3) == true).to_s)
  40. puts('is_prime?(4) == false: ' + (is_prime?(4) == false).to_s)
  41. puts('is_prime?(9) == false: ' + (is_prime?(9) == false).to_s)
  42. puts("===============================================")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement