-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcount_of_squarefree_k-almost_primes.sf
69 lines (47 loc) · 1.65 KB
/
count_of_squarefree_k-almost_primes.sf
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
#!/usr/bin/ruby
# Daniel "Trizen" Șuteu
# Date: 15 March 2021
# https://github.com/trizen
# Count the number of squarefree k-almost primes <= n.
# See also:
# https://en.wikipedia.org/wiki/Almost_prime
func squarefree_almost_prime_count(n, k) {
if (k == 1) {
return n.prime_count
}
var count = 0
func (m, lo, k, j = 1) {
var hi = idiv(n,m).iroot(k)
if (k == 2) {
each_prime(lo, hi, {|p|
count += (prime_count(idiv(n, m*p)) - j++)
})
return nil
}
each_prime(lo, hi, {|p|
__FUNC__(m*p, p+1, k-1, ++j)
})
}(1, 2, k)
return count
}
# Run some tests
for k in (1..10) {
var upto = k.pn_primorial+1e5.irand
var x = squarefree_almost_prime_count(upto, k)
var y = k.squarefree_almost_primes(upto).len
var z = k.squarefree_almost_prime_count(upto)
say "Testing: #{k} with n = #{upto} -> #{x}"
assert_eq(x, y)
assert_eq(x, z)
}
say ''
for k in (1..6) {
say ("Count of squarefree #{'%2d' % k}-almost primes for 10^n: ", 8.of {|n| squarefree_almost_prime_count(10**n, k) })
}
__END__
Count of squarefree 1-almost primes for 10^n: [0, 4, 25, 168, 1229, 9592, 78498, 664579]
Count of squarefree 2-almost primes for 10^n: [0, 2, 30, 288, 2600, 23313, 209867, 1903878]
Count of squarefree 3-almost primes for 10^n: [0, 0, 5, 135, 1800, 19919, 206964, 2086746]
Count of squarefree 4-almost primes for 10^n: [0, 0, 0, 16, 429, 7039, 92966, 1103888]
Count of squarefree 5-almost primes for 10^n: [0, 0, 0, 0, 24, 910, 18387, 286758]
Count of squarefree 6-almost primes for 10^n: [0, 0, 0, 0, 0, 20, 1235, 32396]