-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprimality.ag
97 lines (81 loc) · 1.87 KB
/
primality.ag
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
//Script to check whether a number is prime, using the
//Miller-Rabin primality test.
//(c) Larry T, 2019
//Import dependencies.
import "io";
import "maths";
//Define the function.
let rabinMiller(num, certainty) = {
//Filter out basic primes.
if (num == 2 | num == 3)
{
return true;
}
//Below 2 and % 0? Not prime.
if (num < 2 | num % 2 == 0)
{
return false;
}
//Find the even integer below the number.
let even_num = num - 1;
let s = 0;
//Find lowest odd divisor.
while (even_num % 2 == 0)
{
even_num /= 2;
s++;
}
//Generate a random integer.
let rand = 0;
for (i up to certainty - 1)
{
while (true)
{
rand = random.int(0);
if (rand >= 2 & rand < even_num - 2)
{
break;
}
}
//Done, check for x=1 or x=even-1.
let modPow = maths.modPow(rand, even_num, num);
if (modPow == 1 | modPow == num - 1)
{
continue;
}
//Iterating to check for prime.
for (i up to s - 1)
{
//From 1 upwards.
if (i < 1) { continue; }
modPow = maths.modPow(modPow, 2, num);
if (modPow == 1)
{
return false;
}
else if (modPow == num - 1)
{
break;
}
}
if (modPow != num - 1)
{
return false;
}
}
//All tests have failed to prove composite, so return "probably prime".
return true;
}
//Get the number to check.
print "Enter the number you wish to check for primality.";
let num = int(input.get());
//Check.
let isPrime = rabinMiller(num, 5);
if (isPrime)
{
print "Your number is prime (probably)!";
}
else
{
print "Your number is not prime. :(";
}