Raku / examples

Many examples of Raku code
https://examples.raku.org/
Artistic License 2.0
294 stars 89 forks source link

Incorrect Code for Computing Special Pythagorean Triplet #95

Closed tsalada closed 1 year ago

tsalada commented 1 year ago

Examples prob009-gerdr.pl and gerdr-feeds.pl give an incorrect answer.

The object is to find three numbers, a < b < c, such that (1) a 2 + b 2 = c * 2; and, (2) a + b + c = 1000. The correct answer is 200 375 and 425, but each of the above mentioned scripts gives 31875000 (which is 200 375 * 425).

The attached file (adapted from prob009-gerdr.pl) gives the correct answer (thus indicating that the problem stems from using gather ... take). find_Pythagorean_Triplet.txt

Edit: Full code in the above link is :

#!/usr/bin/env raku

# raku ex_Pythagorean_Triplet_Say.raku

# -------------------------------------------------------------------
#  A Pythagorean triplet is a set of three integers, a < b < c, such
#  that a**2 + b**2 = c**2. Find a triplet where a + b + c = 1000.
# -------------------------------------------------------------------

sub triples($N) {
  for 1..Int((1 - sqrt(0.5)) * $N) -> $a {
    my $u = $N * ($N - 2 * $a);
    my $v = 2 * ($N - $a);

    # If b = u/v is an integer, report triple
    if $u %% $v {
      my $b = $u div $v;
      my $c = $N - $a - $b;
      say "$a $b $c";
    }
  }
}

triples(1000);

# 200 375 425
JJ commented 1 year ago

Good one. Thanks for the report! We'll check it out.

ngaywood commented 1 year ago

Perhaps change the final line from: say [*] .list for gather triples(1000); to: .say for gather triples(1000);

tsalada commented 1 year ago

The solution proposed by ngaywood works on my machine.

In the companion script, prob009-gerdr-feeds.pl, commenting out the line ==> map -> @triple { [*] @triple } \ would yield the correct answer.