CREATE OWN LIBRARY

Happy Number

Back to Programming

Description

A number is said to be a happy number if the number reaches 1 after a number of steps and in each step, the sum of the squares of the digits are calculated and the number is replaced with the sum and again the same step is repeated till it reaches 1.

 

For example, let us consider the number 82.

82+22=64+4=68

62+82=36+64=100

12+02+02=1

Therefore, it is a happy number.

Algorithm

INPUT: A number
OUTPUT: Whether the number is a happy number or not
PROCESS:
Step 1: [Taking the input]
	Read n [the number to be checked]
Step 2: [Checking for Happy Number]
	Set sum<-0
	[Checking for happy number]
	While sum≠1 and sum≠4 repeat
   		Set sum<-0
   		While n>0 repeat
    			Set r<-n mod 10
    			Set sum<-sum+(r×r)
    			Set n<-n/10 
  		[End of ‘while’ loop]
  		Set n<-sum
  	[End of ‘while’ loop]
  	[Printing the result]
  	If sum=1 
 		Print "The number is a Happy Number"
 	Else
 		Print "The number is not a Happy Number"
	[End of ‘if-else’]		
Step 3: Stop.

Code

Time Complexity:

while (sum!=1 && sum!=4)

                {               sum=0;   

                                while(n>0)

                                {

                                r=n%10;

                                sum+=(r*r);

                                n=n/10; 

                                }

                                n=sum;    }

The time complexity of this program is O(m*log10n) where ‘m’ is the number of elements before reaching 1 of which the sum of the square of the digits are to be calculated and ‘n’ is each number that is checked.

 

Space Complexity:

The space complexity of this program is O(1) as it requires a constant number of memory spaces for any given input.