mirror of
https://github.com/TheAlgorithms/Ruby
synced 2024-12-28 22:24:14 +01:00
Add solution for the Project Euler Problem 3
This commit is contained in:
parent
65f50c83a2
commit
963167459e
1 changed files with 29 additions and 0 deletions
29
Project Euler/Problem 3/problem3_sol1.rb
Normal file
29
Project Euler/Problem 3/problem3_sol1.rb
Normal file
|
@ -0,0 +1,29 @@
|
|||
# frozen_string_literal: true
|
||||
|
||||
# The prime factors of 13195 are 5, 7, 13 and 29.
|
||||
# What is the largest prime factor of the number 600851475143
|
||||
|
||||
# find all factors of the given number
|
||||
def get_factors(number)
|
||||
factors = []
|
||||
(1..Math.sqrt(number).to_i).each do |num|
|
||||
if (number % num).zero?
|
||||
factors << num
|
||||
factors << number / num
|
||||
end
|
||||
end
|
||||
factors
|
||||
end
|
||||
|
||||
# determine if a given number is a prime number
|
||||
def prime?(number)
|
||||
get_factors(number).length == 2
|
||||
end
|
||||
|
||||
# find the largest prime
|
||||
def largest_prime_factor(number)
|
||||
prime_factors = get_factors(number).select { |factor| prime?(factor) }
|
||||
prime_factors.max
|
||||
end
|
||||
|
||||
puts largest_prime_factor(600851475143)
|
Loading…
Reference in a new issue