is_perfect_power.sf 526 B

1234567891011121314151617181920212223242526
  1. #!/usr/bin/ruby
  2. # Algorithm for testing if a given number `n` is a perfect
  3. # power (i.e. can be expressed as: n = a^k with k > 1).
  4. # The value of k is returned when n is an exact k-th power, 1 otherwise.
  5. # Algorithm presented in the book:
  6. #
  7. # Modern Computer Arithmetic
  8. # - by Richard P. Brent and Paul Zimmermann
  9. #
  10. func is_perfect_power(n) {
  11. for k in (n.ilog2 `downto` 2) {
  12. if (n.iroot(k)**k == n) {
  13. return k
  14. }
  15. }
  16. return 1
  17. }
  18. say is_perfect_power(1234**14) #=> 14