I’ve been doing the Weekly
Challenges. The
latest
involved Smith numbers and square roots. (Note that this is open
until 10 October 2021.)
Task 1: Integer Square Root
You are given a positive integer $N.
Write a script to calculate the integer square root of the given
number $N.
Please avoid using built-in function.
Which of course one would rarely actually have to do, but it's still
an interesting experiment…
There's a straightforward algorithm on the Wikipedia page based on
Heron's Method, and here's a Rust implementation of it.
fn isqrt(n: u32) -> u32 {
let mut k=n >> 1;
let mut x=true;
while x {
let k1=(k+n/k) >> 1;
if k1 >= k {
x=false;
}
k=k1;
}
k
}
The PostScript looks much the same.
/isqrt {
/n exch def
/k n -1 bitshift def
/x false def
{
/k1 k n k idiv add -1 bitshift def
k1 k ge {
/x true def
} if
/k k1 def
x { exit } if
} loop
k
} def
Task 2: Smith Numbers
Write a script to generate first 10 Smith Numbers in base 10.
These are the numbers for which the digit sum equals the digit sum of
all their prime factors, excluding the trivial case of numbers which
are themselves prime.
Most of these problems lend themselves to single-function solutions,
but this clearly works well with at least one helper, and I ended up
with two (digit-sum and factorisation) because if I were using this
seriously I'd replace the factorisation with something a bit more
efficient.
In Raku. My sumofdigits
takes a list argument, because I'm going to
be passing it a list of prime factors some of the time.
sub sumofdigits(@l) {
my $s=0;
for @l -> $k {
my $l=$k+0;
while ($l > 0) {
$s+=$l % 10;
$l=floor($l/10);
}
}
return $s;
}
There are obviously much better ways to do prime factorisation, but
this one works: trial division, filtering out even numbers after 2.
(divmod
in languages that support it, just because I like it.)
sub factor($nn) {
my $n=$nn;
my @f;
my $ft=2;
while ($n > 1) {
if ($n % $ft == 0) {
push @f,$ft;
$n /= $ft;
} else {
$ft++;
if ($ft % 2 == 0) {
$ft++;
}
}
}
return @f;
}
And with those tools set up, the actual testing function.
sub smith($ccount) {
my $count=$ccount;
my @o;
my $c=1;
while (1) {
$c++;
Factor the candidate number.
my @ff=factor($c);
Discard if prime.
if (@ff.elems == 1) {
next;
}
Check the digit sums (an ad-hoc list for the single value).
if (sumofdigits(($c,))==sumofdigits(@ff)) {
push @o,$c;
$count--;
if ($count <= 0) {
last;
}
}
}
return @o;
}
The PostScript gets a bit more fiddly, with code to squash the list of
factors down into an array just large enough to hold them. (I need to
write some library code to simulate unbounded arrays…)
Full code on
github.
Comments on this post are now closed. If you have particular grounds for adding a late comment, comment on a more recent post quoting the URL of this one.