Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Advanced Ruby coding:
- #Write me a function to generate/print/store the first ānā prime numbers.
- #Accept a input of up to 30 numbers
- input = 30
- #Create an array of Boolean values
- ary = Array.new(input).map{ |value| value = true}
- #0 and 1 are not prime numbers, so we don't need values
- #at index 0 and index 1 in the array
- ary.unshift(nil)
- ary.unshift(nil)
- #start the first iterator from 2
- i = 2
- #initialize an inner iterator
- j = 0
- #Loop until i reaches the square root of input
- while i <= Math.sqrt(input)
- #if the value at index i is true, run the inner loop
- if ary[i]
- #assign the third iterator
- k = 0
- #run the loop until j reaches input
- while j <= input
- #Assign value for j
- j = i**2 + (k * i)
- #set the value at index j as false
- ary[j] = false
- #increment our iterator
- k += 1
- end
- end
- #increment our iterator
- i += 1
- end
- #Create an empty array to hold prime numbers
- prime_numbers = []
- #Loop through the array again
- #Any value that is true, its index is a prime
- ary.each_index do |value|
- if ary[value]
- prime_numbers << value
- end
- end
- #Output the result
- p prime_numbers
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement