A claim that looks true for the first few primes may fail later: the numbers 2 to the power p minus 1, called Mersenne numbers, are prime for p = 2, 3, 5 and 7 but not for p = 11. Your program tests the claim for every prime up to N.
What to build
A program that classifies 2^p - 1 for each prime p up to N.
Requirements
- Read N.
- For every prime p with 2 ≤ p ≤ N, in increasing order, compute V = 2^p − 1.
- If V is prime print
p: V prime. Otherwise printp: V composite, smallest factor f.
Input
One whole number N.
Output
One line for each prime p up to N.
Constraints
2 ≤ N ≤ 23.
Example
Input:
11
Output:
2: 3 prime
3: 7 prime
5: 31 prime
7: 127 prime
11: 2047 composite, smallest factor 23
Why it works
A prime p does not make 2^p − 1 prime, and one composite value is a counterexample to the general claim. Finding the smallest factor by trial division up to the square root of V gives both the verdict and a witness that anyone can check by multiplying.
Examples
11
2: 3 prime 3: 7 prime 5: 31 prime 7: 127 prime 11: 2047 composite, smallest factor 23
5
2: 3 prime 3: 7 prime 5: 31 prime
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
For every prime p up to N compute value = 2**p - 1.
Hint 2
Find the smallest factor f from 2 up to the square root of value; if there is none, the value is prime.
Hint 3
Print one line for each prime p, in increasing order.
Solution
Show one correct solution (try it yourself first)
def smallest_factor(v):
d = 2
while d * d <= v:
if v % d == 0:
return d
d += 1
return v
n = int(input())
for p in range(2, n + 1):
if smallest_factor(p) != p:
continue
v = 2 ** p - 1
f = smallest_factor(v)
if f == v:
print(f"{p}: {v} prime")
else:
print(f"{p}: {v} composite, smallest factor {f}")
▶ Open this solution in the compiler, then press Visualize to watch it run step by step