Last active
December 18, 2015 16:18
-
-
Save GarrisonJ/5810065 to your computer and use it in GitHub Desktop.
FermatPrimalityTest
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <time.h> | |
#include <stdlib.h> | |
#include <math.h> | |
#include <stdio.h> | |
// Test primality of number | |
// | |
// n - Number to test primality | |
// k - Number of times to test n | |
// If k <= 0 then the prime number theorem (1/ln(n)) is used | |
// to give best guess without checking | |
// | |
// Example | |
// FermatPrimalityTest(7,2); | |
// # => 0.75 | |
// | |
// Returns probability of primality | |
float FermatPrimalityTest(int n, int k ){ | |
// If k < 0 then 1/ln(n) is my best guess without checking | |
if ( k <= 0) | |
return 1/log(n); | |
float p = 0.5; | |
srand(time(NULL)); // Set the seed | |
int i; | |
for(i=0; (i<k)&&(p!=0); i++){ | |
int ran = (rand() % (n-1))+1; | |
int a = pow(ran,n); | |
if( a%n == (ran%n) ) | |
p *= p; | |
else | |
p = 0; | |
} | |
return (p==0) ? 0 : (1-p); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment