mirror of
https://github.com/TheAlgorithms/Ruby
synced 2025-02-09 08:46:19 +01:00
Feat: Project Euler Problem 7
This commit is contained in:
parent
e2f6bd9594
commit
bc455a62c5
2 changed files with 42 additions and 0 deletions
|
@ -153,6 +153,8 @@
|
|||
* [Sol2](https://github.com/TheAlgorithms/Ruby/blob/master/project_euler/problem_004/sol2.rb)
|
||||
* Problem 005
|
||||
* [Sol1](https://github.com/TheAlgorithms/Ruby/blob/master/project_euler/problem_005/sol1.rb)
|
||||
* Problem 007
|
||||
* [Sol1](https://github.com/TheAlgorithms/Ruby/blob/master/project_euler/problem_007/sol1.rb)
|
||||
* Problem 020
|
||||
* [Sol1](https://github.com/TheAlgorithms/Ruby/blob/master/project_euler/problem_020/sol1.rb)
|
||||
* Problem 021
|
||||
|
|
40
project_euler/problem_007/sol1.rb
Normal file
40
project_euler/problem_007/sol1.rb
Normal file
|
@ -0,0 +1,40 @@
|
|||
#Project Euler Problem 7: #https://projecteuler.net/problem=7
|
||||
#10001st prime
|
||||
#By listing the first six prime numbers: 2, 3, 5, 7, 11, #and 13, we
|
||||
#can see that the 6th prime is 13.
|
||||
#What is the 10001st prime number?
|
||||
#References: https://en.wikipedia.org/wiki/Prime_number
|
||||
|
||||
def is_prime?(number)
|
||||
value = true
|
||||
if number > 1 and number < 4
|
||||
# 2 and 3 are primes
|
||||
value = true
|
||||
elsif number < 2 or number % 2 == 0 or number % 3 == 0
|
||||
# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
|
||||
value = false
|
||||
end
|
||||
end_range = (Math.sqrt(number) + 1).to_i
|
||||
# All primes number are in format of 6k +/- 1
|
||||
for i in (5..end_range).step(6)
|
||||
if number % i == 0 or number % (i + 2) == 0
|
||||
value = false
|
||||
end
|
||||
end
|
||||
result = value
|
||||
end
|
||||
|
||||
def solution?(nth)
|
||||
primes = Array.new()
|
||||
num = 2
|
||||
while primes.length < nth
|
||||
if is_prime?(num)
|
||||
primes.append(num)
|
||||
end
|
||||
num += 1
|
||||
end
|
||||
primes[primes.length - 1]
|
||||
end
|
||||
|
||||
answer = solution?(1001)
|
||||
p answer
|
Loading…
Add table
Reference in a new issue