764 Asymmetric Diophantine Equation - pythagorean triples.pl 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #!/usr/bin/perl
  2. # Asymmetric Diophantine Equation
  3. # https://projecteuler.net/problem=764
  4. use 5.014;
  5. use warnings;
  6. use ntheory qw(:all);
  7. my $N = powint(10, 7);
  8. my $MOD = powint(10, 9);
  9. sub pythagorean_triples {
  10. my ($limit) = @_;
  11. my @triples;
  12. my $end = sqrtint($limit);
  13. my $sum = 0;
  14. foreach my $n (1 .. $end - 1) {
  15. for (my $m = $n + 1 ; $m <= $end ; $m += 2) {
  16. my $x = ($m*$m - $n*$n);
  17. my $y = ($m * $n) << 1;
  18. my $z = ($m*$m + $n*$n);
  19. last if $x > $limit;
  20. last if $y > $limit;
  21. last if $z > $limit;
  22. gcd($x, $y) == 1 or next;
  23. gcd($x, $z) == 1 or next;
  24. gcd($y, $z) == 1 or next;
  25. if (gcd($n, $m) == 1) { # n and m coprime
  26. foreach my $k(1, 4) {
  27. my $x = $k * $x;
  28. my $y = $k * $y;
  29. my $z = $k * $z;
  30. last if $x > $limit;
  31. last if $y > $limit;
  32. last if $z > $limit;
  33. if (is_square($y) and $x %4 == 0 and gcd($x >> 2, $y, $z) == 1) {
  34. #push @triples, [$x >> 2, sqrtint($y), $z];
  35. $sum = addmod($sum, addmod(addmod(sqrtint($y), ($x >> 2), $MOD), $z, $MOD), $MOD);
  36. }
  37. if (is_square($x) and $y %4 == 0 and gcd($y>>2, $x, $z) == 1) {
  38. #push @triples, [$y>>2, sqrtint($x), $z];
  39. $sum = addmod($sum, addmod(addmod(sqrtint($x), ($y >> 2), $MOD), $z, $MOD), $MOD);
  40. }
  41. }
  42. }
  43. }
  44. }
  45. $sum;
  46. }
  47. say pythagorean_triples(1e4);
  48. say pythagorean_triples(1e7);
  49. __END__
  50. 112851
  51. 248876211
  52. perl 764\ Asymmetric\ Diophantine\ Equation\ -\ pythagorean\ triples.pl 3.56s user 0.01s system 98% cpu 3.612 total