PseudoPrimeTest
SRM 208 · 2004-08-18 · by AdminBrett
SRM 208 · 2004-08-18 · by AdminBrett · Math, Simple Search, Iteration
Problem Statement
Problem Statement
A famous probabilistic primality test makes use of Fermat's Little Theorem from number theory. The theorem states
When computing b^(q-1) % q the numbers can get enormous unless certain measures are taken. For one thing, after each multiplication you can apply the modulus. For example,
p-1 b % p = 1for all primes p, with b satisfying 1 < b < p, and % denoting modulus or remainder. To refresh your memory, a prime is an integer greater than 1 whose only factors are 1 and itself. In order to test some potential prime q we do the following:
- Choose some b-value and compute b^(q-1) % q.
- If this value is not 1 then you know q is not prime.
- If this value is 1, then you are more sure q is prime than before.
When computing b^(q-1) % q the numbers can get enormous unless certain measures are taken. For one thing, after each multiplication you can apply the modulus. For example,
190^11 % 300 = ((190^5 % 300) * (190^6 % 300)) % 300 .In addition, repeated squaring can speed up the exponentiation process. For example,
a^9 = a*a*a*a*a*a*a*a*a requires 8 multiplications but
a^9 = a*((a^2)^2)^2 requires 4 multiplications.
We can combine the two methods above as illustrated in the following example where we compute a^11 % 12: a^11 % 12 = (a * (a^10 % 12)) % 12
a^10 % 12 = (a^5 % 12)^2 % 12
a^5 % 12 = (a * (a^4 % 12)) % 12
a^4 % 12 = (a^2 % 12)^2 % 12
a^2 % 12 = (a*a) % 12
Constraints
- q will be between 3 and 32000 inclusive.
Examples
0)
3 Returns: 3
Since 2^2 % 3 = 4 % 3 = 1 simply return 3.
1)
1729 Returns: 7
Here we have 2^1728 % 1729 = 1 3^1728 % 1729 = 1 4^1728 % 1729 = 1 5^1728 % 1729 = 1 6^1728 % 1729 = 1 7^1728 % 1729 = 742 so 7 is returned.
2)
5 Returns: 5
3)
561 Returns: 3
4)
7 Returns: 7
Submissions are judged against all 73 archived test cases, of which 5 are shown here. Case numbers match the judge’s.
Coding Area
Language: C++17 · define a public class PseudoPrimeTest with a public method int firstFail(int q) · 73 test cases · 2 s / 256 MB per case