Skip to content
GitLab
Projects
Groups
Snippets
Help
Loading...
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
Open sidebar
zlu
projecteuler
Commits
2a2cb399
Commit
2a2cb399
authored
Dec 30, 2009
by
zhao lu
Browse files
optimized algorithm, now it down to less than 1 sec to find answer for p7
parent
0a13f810
Changes
1
Hide whitespace changes
Inline
Sidebyside
Showing
1 changed file
with
18 additions
and
15 deletions
+18
15
p7.rb
p7.rb
+18
15
No files found.
p7.rb
View file @
2a2cb399
# Problem 7
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6^(th) prime is 13.
# What is the 10001^(st) prime number?
# the key is:
# Any number n can have only one primefactor greater than sqrt(n).
# The consequence for primality testing of a number n is: if we cannot find a number f less than
# or equal sqrt(n) that divides n then n is prime: the only primefactor of n is n itself
# another solution is to add i into p and remove it if not prime, but for some reason, maybe related to array
# manipulation, it is a lot slower, about 14 sec to find the answer
t1
=
Time
.
now
p
=
[
2
,
3
,
5
,
7
,
11
,
13
]
(
p
.
max
..
1000000
).
step
(
2
)
do

i

(
p
.
last
+
2
..
1000000
).
step
(
2
)
do

i

j
=
0
stop
=
((
p
.
length
+
1
)
/
2
).
ceil
+
1
while
j
<
stop
&&
(
i
%
p
[
j
]
!=
0
)
do
j
=
j
+
1
end
if
j
==
stop
p
<<
i
end
if
p
.
length
==
10002
puts
p
.
last
break
find
=
true
while
p
[
j
]
<=
Math
.
sqrt
(
i
).
floor
&&
(
j
=
j
+
1
)
do
if
i
%
p
[
j
]
==
0
find
=
false
break
end
end
p
<<
i
if
find
break
if
p
.
length
==
10001
end
puts
"
#{
Time
.
now

t1
}
"
.
to_s
+
" seconds"
puts
"find prime 10001st number "
+
p
.
last
.
to_s
+
" in
#{
Time
.
now

t1
}
"
.
to_s
+
" seconds"
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment