kaprekar | R Documentation |
This function calculates the Kaprekar sequence based on the selected starting integer.
kaprekar(x, base = 10, addZeros = FALSE, maxiter = 1000)
x |
The integer, |
base |
The base of |
addZeros |
If a calculated term has fewer digits than the original |
maxiter |
A "safety switch" to avoid possible lengthy runtimes (when starting with very very large numbers), terminating the function prior to convergence. |
The kaprekar sequence follows simple rules: In the given base, sort the digits in ascending order. Reverse that order, and calculate the absolute value of the difference. Feed that result back to the algorithm. In some cases, the sequence will converge to a value which produces itself. In others, the sequence may fall into a repeating cycle.
A list, containing:
theseq: a vector of bigz
integers representing the sequence, either to convergence or as limited by maxiter
converged: a logical value indicating whether the sequence reached a value or a cycle. This is useful primarily if maxiter
is reached and it's not immediately clear whether convergence occurred.
Carl Witthoft, carl@witthoft.com
https://en.wikipedia.org/wiki/Kaprekar's_routine
(kaprekar(2031))
# $theseq
# Big Integer ('bigz') object of length 5:
# [1] 2031 3087 8352 6174 6174
# $converged
# [1] TRUE
(kaprekar('0099'))
# $theseq
# Big Integer ('bigz') object of length 3:
# [1] 99 0 0
# $converged
# [1] TRUE
(kaprekar('0099', addZeros = TRUE) )
# $theseq
# Big Integer ('bigz') object of length 6:
# [1] 99 9801 9621 8352 6174 6174
# $converged
# [1] TRUE
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.