I am implementing Happy Number program. Happy number is a number which eventually reaches 1 when replaced by the sum of the square of each digit, and a number is not happy number if there are 2 duplicate numbers in the sequence.
For instance:
7 --> 0^2 + 7^2 = 49 --> 4^2 + 9^2 = 97 --> 130 --> 10 --> 1 --> happy number
18 --> 65 --> 61 --> |37| --> 58 --> 89 --> 145 --> 42 --> 20 --> 4 --> 16 --> |37| --> not happy number
My idea is to store the result of each operation to an array, then traverse that array to check if the array has duplicate number. But I think it is inefficient to do that.
So I want to ask how to find an element fast in a random order array, and is there a more efficient solution for the program?
Any help would be appreciated.