064 Odd period square roots.sf 595 B

1234567891011121314151617181920212223242526272829303132333435
  1. #!/usr/bin/ruby
  2. # Daniel "Trizen" Șuteu
  3. # Date: 31 August 2016
  4. # License: GPLv3
  5. # https://github.com/trizen
  6. # https://projecteuler.net/problem=64
  7. # Algorithm from:
  8. # https://web.math.princeton.edu/mathlab/jr02fall/Periodicity/mariusjp.pdf
  9. # Runtime: 5.127 (previously: 6.002s)
  10. func period_length(n) {
  11. var x = n.isqrt
  12. var y = x
  13. var z = 1
  14. var period = 0
  15. do {
  16. y = (((x + y) // z) * z - y)
  17. z = ((n - y*y) // z)
  18. ++period
  19. } while (z > 1)
  20. return period
  21. }
  22. say (1..10000 -> count_by { |n|
  23. n.is_sqr ? false : period_length(n).is_odd
  24. })