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