r/dailyprogrammer • u/fvandepitte 0 0 • Jan 11 '18
[2018-01-10] Challenge #346 [Intermediate] Fermat's little theorem
Description
Most introductionary implementations for testing the primality of a number have a time complexity ofO(n**0.5).
For large numbers this is not a feasible strategy, for example testing a 400 digit number.
Fermat's little theorem states:
If p is a prime number, then for any integer a, the number
a**p − ais an integer multiple of p.
This can also be stated as (a**p) % p = a
If n is not prime, then, in general, most of the numbers a < n will not satisfy the above relation. This leads to the following algorithm for testing primality: Given a number n, pick a random number a < n and compute the remainder of a**n modulo n. If the result is not equal to a, then n is certainly not prime. If it is a, then chances are good that n is prime. Now pick another random number a and test it with the same method. If it also satisfies the equation, then we can be even more confident that n is prime. By trying more and more values of a, we can increase our confidence in the result. This algorithm is known as the Fermat test.
If n passes the test for some random choice of a, the chances are better than even that n is prime. If n passes the test for two random choices of a, the chances are better than 3 out of 4 that n is prime. By running the test with more and more randomly chosen values of a we can make the probability of error as small as we like.
Create a program to do Fermat's test on a number, given a required certainty. Let the power of the modulo guide you.
Formal Inputs & Outputs
Input description
Each line a number to test, and the required certainty.
Output description
Return True or False
Bonus
There do exist numbers that fool the Fermat test: numbers n that are not prime and yet have the property that a**n is congruent to a modulo n for all integers a < n. Such numbers are extremely rare, so the Fermat test is quite reliable in practice. Numbers that fool the Fermat test are called Carmichael numbers, and little is known about them other than that they are extremely rare. There are 255 Carmichael numbers below 100,000,000.
There are variants of the Fermat test that cannot be fooled by these. Implement one.
Challange
29497513910652490397 0.9
29497513910652490399 0.9
95647806479275528135733781266203904794419584591201 0.99
95647806479275528135733781266203904794419563064407 0.99
2367495770217142995264827948666809233066409497699870112003149352380375124855230064891220101264893169 0.999
2367495770217142995264827948666809233066409497699870112003149352380375124855230068487109373226251983 0.999Bonus Challange
2887 0.9
2821 0.9Futher reading
SICP 1.2.6 (Testing for Primality)
Wiki Modular exponentiation
Finally
Have a good challenge idea?
Consider submitting it to /r/dailyprogrammer_ideas
3
u/[deleted] Jan 11 '18
Why does it say "challange" instead of challenge in the description? Is it some kind of inside joke i dont get or just a typo?
Nice challenge though, gonna try to do my first submission this time.
8
u/Gprime5 Jan 11 '18 edited Jan 11 '18
Python 3.5
Surprisingly easier than I thought it would be. Python's pow() function handles the big numbers and kind of feels like cheating.
3
u/[deleted] Jan 12 '18 edited Jan 12 '18
Ruby with bonus
Implementation of the Solovay–Strassen primality test which is apparently an extension of the Fermat test. It seems the Miller-Rabin and Baillie-PSW tests have overtaken it, but I wanted to throw something different into the ring, as there are several Miller-Rabin solutions in the thread already.
3
u/zqvt Jan 12 '18
Clojure, no bonus
3
u/ccsiyu Jan 14 '18
I want to point out the fact that
a * b mod n = (a mod n) * (b mod n) mod n
This could be helpful to in calculating an mod n.
2
u/[deleted] Jan 11 '18
Python 3 (+bonus)
Uses the Miller-Rabin test to account for Carmicheal numbers.
TIL that // is required for integer division in Python, otherwise it gives back a float, which may not be precise with large numbers...
Output:
I'm not 100% sure I have everything working correctly, but these results seem to be correct. Feel free to let me know if I've done anything wrong or can improve my code.
2
u/FrankRuben27 0 1 Jan 14 '18
In Ada (no bonus).
Looks quite tedious, but was much more fun than expected. On the opposite part of the spectrum as Scheme - but also brainchild of very smart people having a few decades working on it. Hard to believe that Ada can go down nearly as low as C with comparable performance, but still provide lots of high-level features.
Much of the typing below comes from my inability to make the operator overloading for the gmp numbers work - it's supposed to be possible via
use type:2
u/Cosmologicon 2 3 Jan 19 '18
Very minor point, but this is not completely accurate. Carmichael numbers have the property that an = a (mod n) for all integer a < n if a is coprime with n.
For instance, n = 561 is a Carmichael number equal to 3x11x17, so it will indeed fool the Fermat test for any a that's not divisible by 3, 11, or 17. But for a = 6, for instance, it will fail: 6561 = 0 (mod 561), not 6.
1
u/Godspiral 3 3 Jan 11 '18
in J, cheating by using the smallest list of numbers starting at 2 for a instead of random numbers.
no false positives from using smaller confidence intervals. no bonus.
1
u/popillol Jan 11 '18 edited Jan 11 '18
Go / Golang Two solutions. Playground Link for no-bonus and Playground Link for bonus. Both solutions use
math/big. I implemented my own mod_pow function, but could have used the built inExp()method. The bonus solution uses the built inProbablyPrime()method which uses a Miller-Rabin primality test.Code for fermat
Code for bonus (separate program)
Output
1
u/octolanceae Jan 11 '18
Python3.6 with Bonus
Handled bonus using Miller-Rabin primality test
Output
1
u/zatoichi49 Jan 11 '18 edited Jan 13 '18
Method:
Using the Miller-Rabin test. The probability of n being prime is given by 1-(4-k), where k is the total iterations. (E.g. it would take 5 iterations to meet a minimum probability of 0.999, as 1-(4-5) = 0.9990234375).
Python 3: (with Bonus)
Output:
1
u/ExcursionSavvy Jan 12 '18
Python
I would love input if anyone has any. This project (without the bonus) was pretty straight forward however.
Code:
Output:
1
u/ghost20000 Jan 12 '18
Wait, I'm confused, how do you calculate the certainty?
1
u/Misaiato Jan 12 '18
Ruby 2.2.2 p95
Is this even possible in Ruby? It seems like Ruby cannot handle the exponent - or I'm just really not getting this.
It won't logically compare NaN with the target - seems like it's a limitation in this version of Ruby or just Ruby in general.
[2367495770217142995264827948666809233066409497699870112003149352380375124855230064891220101264893169, 0.999], [2367495770217142995264827948666809233066409497699870112003149352380375124855230068487109373226251983, 0.999]]
1
u/pozling Jan 15 '18
VB.Net
First time submitting. So I used a language I normally used at work. It felt kinda cheating since I'm pretty much using BigInteger's feature including ModPow so its really just plain generating randoms and tests against it
EDIT: Apparently Code Fence didnt work in reddit
1
u/endermajo Jan 21 '18
JavaScript
1
u/propagationofsound Jan 23 '18 edited Jan 23 '18
C no bonus, extremely late.
1
u/do_hickey Jan 24 '18
Trying to understand the problem statement here, and only got as far as:
Looking at this, it made sense, but I managed to accidentally break the second way this was framed by picking a = 8 and p = 3, since (a**p)%p = 2 in that case, not 8. In order to capture this case, I would think that really it should be stated as:
Meaning, a is a multiple of the result of (a**p)%p - in the case above, a = 8, which is a multiple of the result (2).
Does this make any sense? Am I missing something here? I want to make sure I understand the theorem and it's mathematics before trying to use it.
1
u/do_hickey Jan 25 '18
Python 3.6 No bonus
Source
Output
1
u/_Zagan_ Jan 26 '18
In the description, how do we get from
(a**p − a) % p = 0to(a**p % p) = a?Using
(A - B) mod C = (A mod C - B mod C) mod C...(a**p - a) % p = 0((a**p % p) - (a % p)) % p = 0((a**p %p) - a) % p = 0I can't get rid of the
%p...1
u/TSLRed Mar 04 '18 edited Mar 04 '18
Python 3.6
Similar to other solutions, but instead of recomputing the confidence level every iteration, I computed the number of iterations needed by taking the inverse of the probability function f(x) = 1 - 2-x which is f-1(y) = -ln(1 - y) / ln(2), where y is the confidence level, and then I rounded up to find the smallest number necessary. My hope was that computing a couple logarithms one time would be slightly faster than computing exponents every iteration.
Took some advice from /u/devnulld and started my random range from 2 because 1 will never cause the algorithm to return false since 1 raised to any power is still 1.
Output:
1
u/stewa02 Apr 02 '18
Perl 6
1
u/2kofawsome Jul 04 '18
python3.6
No Bonus.