Infinite loop detection

In general, there is no solution to the Halting problem.

However, in your specific case I can think of a way to detect an infinite loop. In each iteration you calculate a number (the sum of the squares of the digits or the previous number). You can put all those numbers in a Set. If in some iteration you calculate a number that is already in that Set, you know that you are stuck in an infinite loop.

Since the largest sum of squares is bound (for a number with n digits, the largest sum of squares of the digits is 81*n), there is a relatively small number of distinct values you are going to get in your iterations, so if you don't reach 1 and end with a success, you'll reach a value that's already appeared before and report a failure.


While you can't provide a generic infinite loop detection, you can provide a simple one for this use case. You can make the assumption that once you repeat a number, you will always loop forever, so all you need to do is detect a repeated number.

Set<Integer> previous = new HashSet<>();

// in you loop
int sum, number;
do {
   sum = 0;
   int len = String.valueOf(number).length();
   /* Takes out each digit to make the first sum (probably redundant but please ignore)*/
    while(len>0){
        digits = number%k/j;
        j*=10;
        k*=10;
        len--;
        sum += digits*digits;
    }
} while (sum > 1 && previous.add(sum))
if (sum > 1) // no lucky.

In this case, previous.add(sum) will return false is a duplicate is detected.