Happy Number – Replace the number by the sum of the squares of its digits, and repeat the process. At the end, if the number is equals to 1 then it is a Happy Number, or it loops endlessly in a cycle that does not include 1 (if it is not a happy number then this process will end at 4).
For example:
23 is a Happy Number
23 :> 2^2 + 3^2 = 13
13 :> 1^2 + 3^2 = 10
10 :> 1^2 + 0 = 1
As we reached to 1, 23 is a Happy Number.
42 is a UnHappy Number
42 :> 4^2 + 2^2 = 20
20 :> 2^2 + 0 = 4
As we reached to 4, 42 is a UnHappy Number.
C
#include<stdio.h>
int main()
{
int num,temp,sum;
int i,limit;
printf("Enter a Number (upper limit): ");
scanf("%d",&limit);
for(i=1;i<=limit;i++)
{
num=i; // assign next number to check
sum=0; // reset sum
while(sum!=1 && sum!=4)
{
sum=0;
while(num>0)
{
temp=num%10;
sum+=(temp*temp);
num=num/10;
}
num=sum;
}
if(sum==1)
printf(" %d \n",i); // print the current no. if it is happy
}
return 0;
}
C++
#include<iostream.h>
int main()
{
int num,temp,sum;
int i,limit;
cout<<"Enter a Number (upper limit): ";
cin>>limit;
for(i=1;i<=limit;i++)
{
num=i; // assign next number to check
sum=0; // reset sum
while(sum!=1 && sum!=4)
{
sum=0;
while(num>0)
{
temp=num%10;
sum+=(temp*temp);
num=num/10;
}
num=sum;
}
if(sum==1)
cout<<i<<endl; // print the current no. if it is happy
}
return 0;
}
Java
import java.util.Scanner;
class HappyNumberList
{
public static void main(String args[])
{
int num;
int temp;
int sum;
Scanner sc= new Scanner(System.in);
System.out.print("Enter a Number (upper limit): ");
int limit = sc.nextInt();
for (int i = 1;i <= limit;i++)
{
num = i; // assign next number to check
sum = 0; // reset sum
while (sum != 1 && sum != 4)
{
sum = 0;
while (num > 0)
{
temp = num % 10;
sum += (temp * temp);
num = num / 10;
}
num = sum;
}
if (sum == 1)
{
System.out.println(i+"");
}
}
}
}
C#
class HappyNumberList
{
public static void Main()
{
int num;
int temp;
int sum;
Console.Write("Enter a Number (upper limit): ");
int limit = Convert.ToInt32(Console.ReadLine());
for (int i = 1; i <= limit; i++)
{
num = i; // assign next number to check
sum = 0; // reset sum
while (sum != 1 && sum != 4)
{
sum = 0;
while (num > 0)
{
temp = num % 10;
sum += (temp * temp);
num = num / 10;
}
num = sum;
}
if (sum == 1)
{
Console.WriteLine(i + "");
}
}
Console.ReadKey(true);
}
}
Python
limit = int(input("Enter the number (upper limit): "))
for i in range(1, limit + 1):
num = i # num to check
sum = 0 # reset sum
while (sum != 1 and sum != 4):
sum = 0
while (num > 0):
temp = num % 10
sum += (temp * temp)
num = num // 10
num = sum
if (sum == 1):
print(i) # print if no. is Happy
OUTPUT:
Enter a Number (upper limit): 100
1
7
10
13
19
23
28
31
32
44
49
68
70
79
82
86
91
94
97
100