I am writing a program that prints out the sequence of a happy number. A happy number is a number by squaring it leads to
I am writing a program that prints out the sequence of a happy number. A happy number is a number by squaring it leads to 1.
For example 13 is a happy number because 1*1 + 3*3 = 10 and 1*1 + 0*0 = 1
I already wrote the program and it's working execpt that I get a comma at the end. FOR example, I get 13, 10, 1, - Happy. And for 643 i get 643, 61, 37, 58, 89, 145, 42, 20, 4, 16, 37, - Not Happy.
My goal is to print out the output EXACTLY LIKE THIS. Example
input: 13
Output: 13, 10, 1 - Happy
Input 643:
output: 643, 61, 37, 58, 89, 145, 42, 20, 4, 16, 37 - Not Happy.
Here is my code:
import java.util.Scanner;
import java.util.ArrayList; public class Program { public static void main(String[] args){ Scanner input = new Scanner(System.in); ArrayList checkList = new ArrayList(); int x = 0; boolean done = false; while(!done){ System.out.print("Enter a positive integer=>"); x = input.nextInt(); if (x>= 0) done = true; } checkList.add(x); int check = happyNumber(x, checkList); //check if happy number for(int i : checkList){ //print out the check list System.out.print(i + ", "); } if(check == 1) //if the return was 1 its a happy number; System.out.print("------>ls a Happy Number!"); else System.out.print("------>ls not a happy number!"); //Recursive function to find happy number }
public static int happyNumber(int x,ArrayList checkList){ int sum=0; while(x!=0) //while the try x value is not O keep dividing out the digits { int a=x%10; //get the first digit (ls place) sum += a*a; //sum eof the square x /= 10; //now divide out that 10 } sum += x*x; //sum up the last tryx for(int i : checkList){ //check if weve already seen this number if(i == sum){ checkList.add(sum); //add it so we can print it one last time return sum; } } checkList.add(sum); //add it if we havnet seen it if (sum==1) //we know 1 is good return (1); //else if (sum==x) llwe know O is good //return (0); else //therwise keep trying return happyNumber(sum, checkList); } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started