Solution to Project Euler 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 10 001st prime number?
Updated: Sept. 21, 2023 — Training Time: 2 minutes
Overseen by: Archangel Macsika
All Training Resources
Scroll for more menu list
Topic: Project Euler Problem 7: 10001st prime.
Difficulty: Easy.
Objective: 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 10 001st prime number?
Input: None.
Expected Output: 104743.
Sikademy Solution in Java Programming Language
package sikademy;
/**
*
* @author Archangel Macsika
* Copyright (c) Sikademy. All rights reserved
*/
public class SikademyEulerSolution {
public static int sqrt(int x) {
if (x < 0)
throw new IllegalArgumentException("Square root of negative number");
int y = 0;
for (int i = 1 << 15; i != 0; i >>>= 1) {
y |= i;
if (y > 46340 || y * y > x)
y ^= i;
}
return y;
}
public static boolean isPrime(int x) {
if (x < 0)
throw new IllegalArgumentException("Negative number");
if (x == 0 || x == 1)
return false;
else if (x == 2)
return true;
else {
if (x % 2 == 0)
return false;
for (int i = 3, end = sqrt(x); i <= end; i += 2) {
if (x % i == 0)
return false;
}
return true;
}
}
public String run() {
for (int i = 2, count = 0; ; i++) {
if (isPrime(i)) {
count++;
if (count == 10001)
return Integer.toString(i);
}
}
}
public static void main(String[] args) {
SikademyEulerSolution solution = new SikademyEulerSolution();
System.out.println(solution.run());
}
}
Sikademy Solution in Python Programming Language
#
# @author Archangel Macsika
# Copyright (c) Sikademy. All rights reserved.
#
import itertools
def sqrt(x):
assert x >= 0
i = 1
while i * i <= x:
i *= 2
y = 0
while i > 0:
if (y + i)**2 <= x:
y += i
i //= 2
return y
# Tests whether the given integer is a prime number.
def is_prime(x):
if x <= 1:
return False
elif x <= 3:
return True
elif x % 2 == 0:
return False
else:
for i in range(3, sqrt(x) + 1, 2):
if x % i == 0:
return False
return True
def compute():
ans = next(itertools.islice(filter(is_prime, itertools.count(2)), 10000, None))
return str(ans)
if __name__ == "__main__":
print(compute())