RogerBW's Blog

The Weekly Challenge 175: Perfect Sunday 26 July 2022

I’ve been doing the Weekly Challenges. The latest involved date calculations and number theory. (Note that this is open until 31 July 2022.)

Task 1: Last Sunday

Write a script to list last sunday of every month in the given year.

Date calculations are one of those things like cryptography with all sorts of traps for the unwary, so I've used system libraries wherever possible. For Perl I used the good library rather than the older built-ins:

use DateTime;

sub lastsunday($year) {
  my @o;
  foreach my $month (1..12) {
    my $dt = DateTime->last_day_of_month(year => $year,
                                         month => $month);
    my $dl = $dt->day_of_week();
    if ($dl != 7) {
      $dt->subtract(days => $dl);
    }
    push @o,$dt->strftime('%Y-%m-%d');
  }
  return \@o;
}

Raku's built-in Date class also offers a last-date-in-month: it works slightly differently, but the basic idea is the same. For the other languages, which don't have this, I bodged it by going back a day from the first day of the next month, as in this Kotlin (which uses the LocalDate and Period libraries from Java):

fun lastsunday(year0: Int): List<String> {
    var year = year0
    var o = ArrayList<String>()
    val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
    for (month0 in 2..13) {
        var month = month0
        if (month0 == 13) {
            year += 1
            month -= 12
        }
        var dt = LocalDate.of(year,month,1).minusDays(1)
        val dl = dt.dayOfWeek.getValue()
        if (dl < 7) {
            dt = dt.minusDays(dl.toLong())
        }
        o.add(dt.format(formatter))
    }
    return o
}

Some languages give a Sunday as 0 in their day-of-week function, which lets me remove the test on dl.

Lua can convert date-times back and forth to an internal representation, but can't do much with them: on Unix it uses seconds since the epoch as that representation, but there's no guarantee of the size or base of the unit elsewhere, so I'd have had to write day-of-the-week code from scratch. So I didn't write a Lua version of this.

Of course, PostScript has even less date support, but as it turns out I'd already written a Julian day number conversion library (originally for challenge #132), which does the job nicely here. (I suspect I should write a sprintf / strftime-style formatting function.)

Task 2: Perfect Totient Numbers

Write a script to generate first 20 Perfect Totient Numbers.

Given the speed of modern languages and machines, I didn't bother with much optimisation. It would be faster (though of course it would use more memory) to keep a map of iterated totient values to avoid repeated calculation; but it was hot and I felt little enthusiasm for writing that across multiple languages.

Here's the Python for the Euler totient (I've written gcd functions before for languages that need them):

def eulertotient(n):
  return sum(1 for k in range(1,n+1) if gcd(n,k) == 1)

Then the iterated version (with an optimisation you should remove if you actually want the iterated totient value for some reason - p > n0 implies that p is not equal to n0 and since that's all we care about we needn't calculate it further).

def iteratedtotient(n0):
  p = 0
  n = n0
  while True:
    n = eulertotient(n)
    p += n
    if n == 1:
      break
    if p > n0:
      break
  return p

Finally the list-building top-level function:

def perfecttotient(ct):
  o = []
  n = 1
  while len(o) < ct:
    n += 1
    if iteratedtotient(n) == n:
      o.append(n)
  return o

The algorithm in other languages is basically the same.

Full code on github.

See also:
Perl Weekly Challenge 132: Hash on the Mirror

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 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