count_of_pythagorean_triples_with_side_n.sf 900 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. #!/usr/bin/ruby
  2. # Formula for counting the number of integer-sided right triangles with n as a hypotenuse or leg.
  3. # See also:
  4. # https://oeis.org/A046081
  5. # https://projecteuler.net/problem=827
  6. func count_of_pythagorean_triples(n) {
  7. # Inspired by the PARI/GP program by Michel Marcus, Mar 07 2016.
  8. # https://oeis.org/A046081
  9. var n0_sigma0 = 1
  10. var n1_sigma0 = 1
  11. for p,e in (n.factor_exp) {
  12. if (p == 2) {
  13. n0_sigma0 *= (2*e - 1)
  14. }
  15. else {
  16. n0_sigma0 *= (2*e + 1)
  17. if (p % 4 == 1) {
  18. n1_sigma0 *= (2*e + 1)
  19. }
  20. }
  21. }
  22. (n0_sigma0 + n1_sigma0)/2 - 1
  23. }
  24. say count_of_pythagorean_triples(48)
  25. say count_of_pythagorean_triples(8064000)
  26. assert_eq(
  27. 1000.of(count_of_pythagorean_triples).slice(1),
  28. 1000.of { .sqr.sum_of_squares.len.dec + .sqr.diff_of_squares.len.dec }.slice(1)
  29. )