RogerBW's Blog

Perl Weekly Challenge 133: Rooting the Smith 06 October 2021

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.

Search
Archive
Tags 1920s 1930s 1940s 1950s 1960s 1970s 1980s 1990s 2000s 2010s 3d printing action advent of code aeronautics aikakirja anecdote animation anime army astronomy audio audio tech base commerce battletech beer boardgaming book of the week bookmonth chain of command children chris chronicle church of no redeeming virtues cold war comedy computing contemporary cornish smuggler cosmic encounter coup covid-19 crime crystal cthulhu eternal cycling dead of winter doctor who documentary drama driving drone ecchi economics en garde espionage essen 2015 essen 2016 essen 2017 essen 2018 essen 2019 essen 2022 essen 2023 essen 2024 existential risk falklands war fandom fanfic fantasy feminism film firefly first world war flash point flight simulation food garmin drive gazebo genesys geocaching geodata gin gkp gurps gurps 101 gus harpoon historical history horror hugo 2014 hugo 2015 hugo 2016 hugo 2017 hugo 2018 hugo 2019 hugo 2020 hugo 2021 hugo 2022 hugo 2023 hugo 2024 hugo-nebula reread in brief avoid instrumented life javascript julian simpson julie enfield kickstarter kotlin learn to play leaving earth linux liquor lovecraftiana lua mecha men with beards mpd museum music mystery naval noir non-fiction one for the brow opera parody paul temple perl perl weekly challenge photography podcast politics postscript powers prediction privacy project woolsack pyracantha python quantum rail raku ranting raspberry pi reading reading boardgames social real life restaurant reviews romance rpg a day rpgs ruby rust scala science fiction scythe second world war security shipwreck simutrans smartphone south atlantic war squaddies stationery steampunk stuarts suburbia superheroes suspense television the resistance the weekly challenge thirsty meeples thriller tin soldier torg toys trailers travel type 26 type 31 type 45 vietnam war war wargaming weather wives and sweethearts writing about writing x-wing young adult
Special All book reviews, All film reviews
Produced by aikakirja v0.1