Advertisement
Guest User

Untitled

a guest
May 1st, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.12 KB | None | 0 0
  1. #Advanced Ruby coding:
  2. #Write me a function to generate/print/store the first ā€œnā€ prime numbers.
  3. #Accept a input of up to 30 numbers
  4. input = 30
  5. #Create an array of Boolean values
  6. ary = Array.new(input).map{ |value| value = true}
  7.  
  8. #0 and 1 are not prime numbers, so we don't need values
  9. #at index 0 and index 1 in the array
  10. ary.unshift(nil)
  11. ary.unshift(nil)
  12.  
  13. #start the first iterator from 2
  14. i = 2
  15.  
  16. #initialize an inner iterator
  17. j = 0
  18.  
  19. #Loop until i reaches the square root of input
  20. while i <= Math.sqrt(input)
  21.  
  22. #if the value at index i is true, run the inner loop
  23. if ary[i]
  24.  
  25. #assign the third iterator
  26. k = 0
  27.  
  28. #run the loop until j reaches input
  29. while j <= input
  30.  
  31. #Assign value for j
  32. j = i**2 + (k * i)
  33.  
  34. #set the value at index j as false
  35. ary[j] = false
  36.  
  37. #increment our iterator
  38. k += 1
  39. end
  40. end
  41. #increment our iterator
  42. i += 1
  43. end
  44. #Create an empty array to hold prime numbers
  45. prime_numbers = []
  46.  
  47. #Loop through the array again
  48. #Any value that is true, its index is a prime
  49. ary.each_index do |value|
  50. if ary[value]
  51. prime_numbers << value
  52. end
  53. end
  54.  
  55. #Output the result
  56. p prime_numbers
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement