Created
October 6, 2012 19:16
-
-
Save incogneato/3845837 to your computer and use it in GitHub Desktop.
Prime Factors Again
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Create a method which takes integers and returns their prime factors in an array. | |
# primes are integers greater than 1, | |
# divisible only by 1 and themselves. | |
# primes > 2 are odd numbers. | |
# prime factors of integer <= square root of integer parameter (n) | |
def primes(n) | |
puts | |
puts | |
# initialize the array to add the prime factors | |
prime_factors = [] | |
factor = n | |
# iterate over range, up to sqrt integer | |
(2).upto(Math.sqrt(factor).to_i). each do |divisor| | |
# for divisor in (2..factor) do | |
# Math.sqrt(factor).to_i.downto(2).each do |divisor| | |
puts "Finding primes from #{divisor} to #{factor}." | |
puts | |
puts "Checking now if #{divisor} is a factor." | |
if factor % divisor == 0 | |
puts | |
puts "--> #{factor} is divisible by #{divisor}." | |
prime_factors << divisor | |
puts | |
puts "Factors array now set: #{prime_factors.inspect}" | |
quotient = factor / divisor | |
factor = quotient | |
end #/if loop | |
end #/do | |
puts | |
puts "Exiting loop; #{factor} is the last quotient to've passed if statement." | |
prime_factors << factor | |
p prime_factors | |
end | |
# primes(256) # should print [2,2,2,2,2,2,2,2] | |
# primes(100) # should print [2,2,5,5] | |
# primes(81) # should print [3,3,3,3] | |
# primes(10) # should print [2,5] | |
primes(8) # should print [2,2,2] --> current prints [2,4] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment