coding for food
[Ruby] exercise _ Prime Factors
silveryen
2022. 8. 7. 00:54
Write a method prime_factors that takes in a number and returns an array containing all of the prime factors of the given number.
def prime_factors(num)
end
print prime_factors(24) #=> [2, 3]
puts
print prime_factors(60) #=> [2, 3, 5]
puts
#my code
def prime_factors(num)
i = 1
new_arr = []
while i <= num
if num % i == 0
new_arr << i
end
i += 1
end
new_arr.select { |prime| factor?(prime) }
end
def factor?(prime)
if prime < 2
return false
end
(2...prime).each do |factor|
if prime % factor == 0
return false
end
end
return true
end
print prime_factors(24) #=> [2, 3],
puts
print prime_factors(60) #=> [2, 3, 5]
puts
def prime_factors(num)
prime_facts = []
(1..num).each do |i|
if num % i == 0 && prime?(i)
prime_facts << i
end
end
return prime_facts
end
def prime?(n)
if n < 2
return false
end
(2...n).each do |i|
if n % i == 0
return false
end
end
return true
end
print prime_factors(24) #=> [2, 3]
puts
print prime_factors(60) #=> [2, 3, 5]
puts