title: isHappy function in Java
body: <p>I am trying to make a method isHappy that will return True if a given integer is a happy number, and false otherwise. </p>
  
  <p>A number is happy if one can reach the number 1 by repeatedly taking the sum of the squares of its digits. e.g. 397 is a happy number:</p>
  
  <p>397 -> 139 -> 91 -> 82 -> 100 -> 1</p>
  
  <p>Numbers that are not happy will loop and thus never reach 1. e.g. 123 is not a happy number:</p>
  
  <p>123 -> 14 -> 17 -> 50 -> 25 -> 29 -> 85 -> 89 -> 145 -> 42 -> 20 -> 4 -> 16 -> 37 -> 58 -> 89 -> ...</p>
  
  <p>To find out if a number is happy or not, I tried to use a recursive algorithm that requires three extra items to be maintained.  1) A number that has been seen already that will be remembered for a fixed number of steps, 2) the number of remaining steps that we will remember this number for, and 3) once we forget this number, how long we will remember the next number we see for (which will be one step longer than the last number was remembered for).</p>
  
  <p>When the number we are remembering becomes the same as the next number in the sequence,
  we know we have reached a loop and can then stop.</p>
  
  <p>This is my code :</p>
  
  <pre><code>public static boolean isHappy(int n) {
       assert n &gt; 0 : "n should be positive";
       // Post: Returns true if a number is 'happy', unless false.
       return checkHappiness (n, n/2, n/8, n/16);  
    }
  
  private static boolean checkHappiness (int n, int r, int t, int nt) {
      // A (hidden) helper function of 'isHappy' that counts additional parameters.
      if (n == 1) return true;
       else if (n == r) return false;
        else if (t &gt; 0) return checkHappiness (sumSquareDigits (n),r,t-1,nt);
         else if (t == 0) return checkHappiness (n+1, n, nt, nt+1);
      return true;
    }
  </code></pre>
  
  <p>I should mention that the arguments of the helper function are: the current number (n), the number currently being remembered (r), how long that number will be remembered for (t), and the amount of time the next remembered number will be remembered for (nt).</p>
  
  <p>This works fine except with the case of 2. For some reason it thinks 2 is a happy number but it is not! Can anyone see where is my error? Thanks!</p>