Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Check whether the given number is Wagstaff prime or not in Python
A Wagstaff prime is a prime number that can be expressed in the form (2q + 1)/3, where q is an odd prime number. These numbers are named after mathematician Samuel S. Wagstaff Jr.
Example
For n = 683, we can verify it's a Wagstaff prime because 683 = (211 + 1)/3, where q = 11 is an odd prime.
Algorithm
To check if a number is a Wagstaff prime, we need to:
- Verify the number itself is prime
- Check if (num × 3 + 1) is a power of 2
- Verify that the exponent is an odd prime
Implementation
def isPrime(num):
if num < 2:
return False
if num == 2:
return True
if num % 2 == 0:
return False
for i in range(3, int(num**0.5) + 1, 2):
if num % i == 0:
return False
return True
def power_of_two(num):
return num > 0 and (num & (num - 1)) == 0
def find_exponent(power_of_2):
"""Find the exponent q where 2^q = power_of_2"""
if power_of_2 <= 0:
return -1
exponent = 0
while power_of_2 > 1:
power_of_2 //= 2
exponent += 1
return exponent
def is_wagstaff_prime(num):
# Check if num is prime
if not isPrime(num):
return False
# Check if (num * 3 + 1) is a power of 2
candidate = num * 3 + 1
if not power_of_two(candidate):
return False
# Find the exponent q
q = find_exponent(candidate)
# Check if q is an odd prime
if q <= 1 or q % 2 == 0:
return False
return isPrime(q)
# Test with the given example
n = 683
result = is_wagstaff_prime(n)
print(f"Is {n} a Wagstaff prime? {result}")
# Verify the calculation
if result:
q = find_exponent(n * 3 + 1)
verification = (2**q + 1) // 3
print(f"Verification: (2^{q} + 1) / 3 = {verification}")
Is 683 a Wagstaff prime? True Verification: (2^11 + 1) / 3 = 683
Testing with More Examples
# Test with known Wagstaff primes
wagstaff_candidates = [3, 11, 43, 683, 2731, 43691]
for num in wagstaff_candidates:
result = is_wagstaff_prime(num)
if result:
q = find_exponent(num * 3 + 1)
print(f"{num} is a Wagstaff prime with q = {q}")
else:
print(f"{num} is not a Wagstaff prime")
3 is a Wagstaff prime with q = 3 11 is a Wagstaff prime with q = 5 43 is a Wagstaff prime with q = 7 683 is a Wagstaff prime with q = 11 2731 is a Wagstaff prime with q = 13 43691 is a Wagstaff prime with q = 17
Key Points
- Wagstaff primes are rare and follow the formula (2q + 1)/3
- The exponent q must be an odd prime number
- We verify by checking if num × 3 + 1 equals 2q
- Only a few Wagstaff primes are known for small values of q
Conclusion
A Wagstaff prime checker verifies if a number fits the form (2q + 1)/3 where q is an odd prime. The algorithm checks primality, power-of-two properties, and validates the exponent.
Advertisements
