Repository navigation
Expand file tree
/
Copy path1.25.rb
More file actions
89 lines (76 loc) · 1.24 KB
/
Copy path1.25.rb
File metadata and controls
89 lines (76 loc) · 1.24 KB
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
def smallest_divisor(n)
find_divisor(n, 2)
end
def divides?(a, b)
b % a == 0
end
def find_divisor(n, test_divisor)
if test_divisor ** 2 > n
n
elsif divides?(test_divisor, n)
test_divisor
else
find_divisor(n, test_divisor + 1)
end
end
def prime?(n)
n == smallest_divisor(n)
end
def expmod(base, exp, m)
fast_exp(base, exp) % m
end
def fast_exp(b,n)
if n == 0
1
elsif n.even?
fast_exp(b, n / 2) ** 2
else
b * (fast_exp(b, n-1))
end
end
def fermat_test(n)
a = 1 + rand(n-1)
expmod(a,n,n) == a
end
def fast_prime?(n,times)
if times == 0
true
elsif fermat_test(n)
fast_prime?(n, times - 1)
else
false
end
end
def timed_prime_test(n)
puts
print n
start_prime_test(n, Time.now.to_f)
end
def start_prime_test(n, start_time)
if fast_prime?(n,5)
report_prime(Time.now.to_f - start_time)
return true
else
return false
end
end
def report_prime(elapsed_time)
print " *** "
print elapsed_time
end
def first_3_primes_from(m)
q = 0
loop do
if timed_prime_test(m)
q += 1
if q == 3
break
end
end
m += 1
end
end
first_3_primes_from(1000)
first_3_primes_from(10000)
first_3_primes_from(100000)
first_3_primes_from(1000000)