Floyd’s Tortoise and Hare
原题
Write an algorithm to determine if a number is “happy”.
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
代码实现
public class Solution {
public bool IsHappy(int n) {
int slow =n, fast = n;
do{
slow = getSum(slow);
fast = getSum(fast);
fast = getSum(fast);
}while(slow!=fast);
return slow==1;
}
public int getSum(int n){
int sum=0;
int tmp = n;
while(tmp>0){
int i = tmp%10;
sum+=i*i;
tmp = tmp/10;
}
return sum;
}
}
例19根据以上规则映射后的序列为:
[19, 82, 68, 100, 1, 1, 1, ...]
为Happy Number
例20的映射后的序列为:
[4,16,37,58,89,145,42,20,4,16,...]
例38映射后的序列为:
[73,58,89,145,42,20,4,16,37,58,89,...]
扩展
Floyd’s Tortoise and Hare
The key insight in the algorithm is that, for any integers i ≥ μ and k ≥ 0, xi = xi + kλ, where λ is the length of the loop to be found and μ is the index of the first element of the cycle. In particular, i = kλ≥ μ, if and only if xi = x2i. Thus, the algorithm only needs to check for repeated values of this special form, one twice as far from the start of the sequence as the other, to find a period ν of a repetition that is a multiple of λ. Once ν is found, the algorithm retraces the sequence from its start to find the first repeated value xμ in the sequence, using the fact that λ divides ν and therefore that xμ = xμ +v. Finally, once the value of μ is known it is trivial to find the length λ of the shortest repeating cycle, by searching for the first position μ + λ for which xμ + λ = xμ. The algorithm thus maintains two pointers into the given sequence, one (the tortoise) at xi, and the other (the hare) at x2i. At each step of the algorithm, it increases i by one, moving the tortoise one step forward and the hare two steps forward in the sequence, and then compares the sequence values at these two pointers. The smallest value of i > 0 for which the tortoise and hare point to equal values is the desired value ν.