I am trying to create a function that returns the smallest prime factor of a given number:
require 'prime'
def findSmallestPrimeFactor(number)
return 2 if number.even?
return number if Prime.prime? number
arrayOfFactors = (1..number).collect { |n| n if number % n == 0 }.compact
arrayOfFactors.each { |n| arrayOfFactors.pop(n) unless Prime.prime? n }
return arrayOfFactors[0]
end
findSmallestPrimeFactor(13333) returns 1, which should not be happening since 1 should be removed from arrayOfFactors during line 7, as Prime.prime? 1 returns false
It sometimes returns nothing:
puts findSmallestPrimeFactor(13335) # => returns empty line
This issue only occurs when working with a number that is not even and is not prime, i.e lines 4 and 5 are ignored.
Also, when this is finished I will be passing some very large numbers through it. Is there any shorter or more efficient way to do lines 6-8 for larger numbers?
Aucun commentaire:
Enregistrer un commentaire