|
| 1 | +#!/usr/bin/perl |
| 2 | + |
| 3 | +# Daniel "Trizen" Șuteu |
| 4 | +# Date: 05 September 2025 |
| 5 | +# https://github.com/trizen |
| 6 | + |
| 7 | +# Count the number of B-rough numbers <= n. |
| 8 | + |
| 9 | +# See also: |
| 10 | +# https://en.wikipedia.org/wiki/Rough_number |
| 11 | + |
| 12 | +use 5.020; |
| 13 | +use ntheory qw(:all); |
| 14 | +use experimental qw(signatures); |
| 15 | + |
| 16 | +sub my_rough_count($n, $k) { |
| 17 | + |
| 18 | + my @P = @{primes($k - 1)}; |
| 19 | + |
| 20 | + return $n if (@P == 0); |
| 21 | + |
| 22 | + my %cache; |
| 23 | + |
| 24 | + sub ($n, $a) { |
| 25 | + |
| 26 | + my $key = "$n,$a"; |
| 27 | + |
| 28 | + return $cache{$key} |
| 29 | + if exists $cache{$key}; |
| 30 | + |
| 31 | + # Initial count: odd numbers ≤ n |
| 32 | + my $count = $n - ($n >> 1); |
| 33 | + |
| 34 | + # Inclusion-Exclusion principle |
| 35 | + for my $j (1 .. $a - 1) { |
| 36 | + last if ($P[$j] > $n); |
| 37 | + $count -= __SUB__->(divint($n, $P[$j]), $j); |
| 38 | + } |
| 39 | + |
| 40 | + $cache{$key} = $count; |
| 41 | + }->($n, scalar @P); |
| 42 | +} |
| 43 | + |
| 44 | +foreach my $p (@{primes(30)}) { |
| 45 | + say "Φ(10^n, $p) for n <= 10: [", join(', ', map { my_rough_count(powint(10, $_), $p) } 0 .. 10), "]"; |
| 46 | +} |
| 47 | + |
| 48 | +__END__ |
| 49 | +Φ(10^n, 2) for n <= 10: [1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000, 10000000000] |
| 50 | +Φ(10^n, 3) for n <= 10: [1, 5, 50, 500, 5000, 50000, 500000, 5000000, 50000000, 500000000, 5000000000] |
| 51 | +Φ(10^n, 5) for n <= 10: [1, 3, 33, 333, 3333, 33333, 333333, 3333333, 33333333, 333333333, 3333333333] |
| 52 | +Φ(10^n, 7) for n <= 10: [1, 2, 26, 266, 2666, 26666, 266666, 2666666, 26666666, 266666666, 2666666666] |
| 53 | +Φ(10^n, 11) for n <= 10: [1, 1, 22, 228, 2285, 22857, 228571, 2285713, 22857142, 228571428, 2285714285] |
| 54 | +Φ(10^n, 13) for n <= 10: [1, 1, 21, 207, 2077, 20779, 207792, 2077921, 20779221, 207792207, 2077922077] |
| 55 | +Φ(10^n, 17) for n <= 10: [1, 1, 20, 190, 1917, 19181, 191808, 1918081, 19180820, 191808190, 1918081917] |
| 56 | +Φ(10^n, 19) for n <= 10: [1, 1, 19, 179, 1806, 18053, 180524, 1805251, 18052535, 180525355, 1805253568] |
| 57 | +Φ(10^n, 23) for n <= 10: [1, 1, 18, 170, 1711, 17103, 171021, 1710234, 17102401, 171024023, 1710240224] |
| 58 | +Φ(10^n, 29) for n <= 10: [1, 1, 17, 163, 1634, 16361, 163586, 1635877, 16358819, 163588196, 1635881952] |
0 commit comments