C Program to Check Happy Number Or Not
In Number Theory, A Happy Number is a Number Which
Eventually reaches 1 when replaced by the sum of the square of each digit.
Example :
Given Number : 13
13 is a Happy Number
Because
13 = ( 1*1 )+( 3*3 ) = 1 + 9 = 10
10 = ( 1*1 )+( 0*0 ) = 1 + 0 = 1
Given Number : 28
28 is a Happy Number
Because
28 = ( 2*2 ) +( 8*8 ) = 4 + 64 = 68
68 = ( 6*6 ) +( 8*8 ) = 36+ 64 = 100
100= ( 1*1)+( 0*0 )+ ( 0*0 ) = 1 + 0 + 0 = 1
you can use the following algorithm:
- Read the input number.
- Initialize a variable sum to 0.
- Create a copy of the input number.
- While num is not equal to 0, perform the following steps:
- Get the last digit of the num by using the modulo operator (%).
- Square the last digit and add it to sum.
- Divide the num by 10 to remove the last digit.
- if num = 0 and sum>=10
- Reset num to sum and sum to 0.
- Check if the sum of the number is equal to 1.
- If it is 1, the number is a Happy Number.
- If it is Not 1, the number is Not a Happy Number.
Please note that this implementation assumes that the input number is a positive integer. You may need to add additional checks for negative numbers or other cases depending on your requirements.
Here is an example implementation in CSource Code
//C Program to Check Happy Number Or Not ?
#include<stdio.h>
#include<conio.h>
void main()
{
int num,Rd,sum=0;
printf("Enter a Number To Check : ");
scanf("%d",&num);
while( num!=0 )
{
Rd = num % 10 ;
sum = sum + Rd * Rd ;
num = num / 10 ;
if( num==0 && sum>=10)
{
num=sum;
sum=0;
}
}
if( sum==1 )
printf("It is a Happy Number . ");
else
printf("It is Not a Happy Number . ");
getch();
}
Output
Sample Input :
Enter a Number To Check : 28
Sample Output:
It is a Happy Number
Sample Input :
Enter a Number To Check : 12
Sample Output:
It is Not a Happy Number
Looping Related Programs
- C Program to Check Perfect Number or Not
- C Program to Check Prime Number or Not
- C Program to Check Twin Prime Number or Not
- C Program to Check Duck Number or Not
- C Program to Check Niven Or Harshad Number or Not
- C Program to Check Spy Number or Not
- C Program to Check Palindrome Number or Not
- C Program to Check Neon Number or Not
- C Program to Check Armstrong Number or Not
- C Program to Check Strong (Krishnamurthy)Number or Not
- C Program to Check Automorphic Number or Not