Program opened below. You can scroll through the algorithm, Java code and output.

Happy Number Using Recursion

Download .java

Question

Read a positive integer and use recursion to test whether repeatedly summing squares of its digits eventually produces 1.

Step 1: Begin execution and input a positive integer. Step 2: Reject zero or negative input. Step 3: Define a recursive function for finding the sum of squared digits. Step 4: Use zero as the base case for the digit-squares function. Step 5: Take the last digit using remainder ten. Step 6: Square that digit. Step 7: Recursively process the remaining digits after division by ten. Step 8: Add the square and the recursive result. Step 9: Define a second recursive function to determine happiness. Step 10: Return true immediately when the number becomes one. Step 11: Return false when the number reaches four, which is part of the unhappy cycle. Step 12: Otherwise find the sum of the squares of the digits. Step 13: Recursively test this new value. Step 14: Display Happy or Not Happy using the returned answer. Step 15: Stop.
Java
import java.util.*;
class HappyRecursive {
    static int digitSquares(int n) {
        if (n == 0) {
            return 0;
        }
        int digit = n % 10;
        return digit * digit + digitSquares(n / 10);
    }
    static boolean happy(int n) {
        if (n == 1) {
            return true;
        }
        if (n == 4) {
            return false;
        }
        return happy(digitSquares(n));
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        if (n < 1) {
            System.out.println("Invalid number");
            return;
        }
        System.out.println(happy(n) ? "Happy" : "Not Happy");
    }
}
Input: 28 Output: Happy
← Previous Program 10 of 84 Next →

Share a comment or request a program

Use this form to send a comment, report an issue, or suggest a new practical. Your message will be saved for review by the school.