-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathp_euler_003.rb
More file actions
93 lines (72 loc) · 1.91 KB
/
p_euler_003.rb
File metadata and controls
93 lines (72 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#!/usr/bin/ruby -w
=begin
Solution for Project Euler, problem 3, in ruby
=end
$primes = [2]
=begin
Determine if candidate is a factor of goal
Coerce the goal into a float and divide by candidate. If the result is an
integer then the candiadte is a factor of goal.
=end
def is_factor(goal, candidate)
return candidate != 0 && goal * 1.0 / candidate % 1 == 0
end
=begin
Determine if a number is a prime
=end
def is_prime?(n, existing_primes=[])
if n == 2
return true
elsif n % 2 == 0
return false
else
existing_primes.each { |prime| return false if n % prime == 0 }
return true
end
end
=begin
Add another prime to the list of primes.
We will build our list of primes dynamically as large limits will would mean
we spend forever calculating primes we never use.
=end
def add_prime(limit=10000000)
i = $primes[-1] + 1
while i <= limit * 1.0 do
if is_prime?(i, $primes)
$primes.push(i)
return true
end
i +=1
end
end
=begin Solution
1. Check for factors, starting with the smallest prime
2. If goal number is prime, add to list
3. If factor, add factor to the list. Replace original number with co-product
4. Else try again with next prime
5. Repeat until product is 0
6. Return the hightst prime factor
=end
def find_highest_prime_factor(goal)
product = goal
factors = []
index = 0
while product > 0 do
if $primes.length >= index
add_prime(goal)
end
if $primes.include? product
factors.push(product)
product = 0
elsif is_factor(product, $primes[index])
factors.push($primes[index])
product /= $primes[index]
end
index +=1
end
return factors[-1]
end
if find_highest_prime_factor(13195) == 29
puts find_highest_prime_factor(600851475143)
else puts 'Test failed'
end