Skip to content

Commit cc6ac8f

Browse files
authored
Create happyNumber.c
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. Return True if n is a happy number, and False if not.
1 parent c5c05c2 commit cc6ac8f

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed

happyNumber.c

+93
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
#include <stdio.h>
2+
#include <conio.h>
3+
4+
int sqsum (int n)
5+
{
6+
int r,s=0;
7+
while(n!=0)
8+
{
9+
r=n%10;
10+
s+=r*r;
11+
n/=10;
12+
}
13+
return s;
14+
}
15+
int psqsum(int n)
16+
{
17+
int r,s=0;
18+
while(n!=0)
19+
{
20+
r=n%10;
21+
s+=r*r;
22+
n/=10;
23+
printf("%d+",r*r);
24+
}
25+
printf("=%d\n",s);
26+
return s;
27+
}
28+
int main()
29+
{
30+
int num,sum,ch,n1,n2,i;
31+
printf("Select the method : 1.Easy 2.Medium 3.Hard\n");
32+
scanf("%d",&ch);
33+
switch(ch)
34+
{
35+
case 1 :
36+
printf("Enter the number : ");
37+
scanf("%d",&num);
38+
sum = num ;
39+
while(sum>1)
40+
{
41+
sum = sqsum(sum);
42+
if (sum == 4)
43+
break;
44+
45+
}
46+
if (sum==1)
47+
printf("%d is Happy number",num);
48+
if (sum==4)
49+
printf("%d is Unhappy number",num );
50+
break;
51+
case 2 :
52+
printf("Enter the range : \n");
53+
scanf("%d%d",&n1,&n2);
54+
printf("Happy numbers in the given range are : ");
55+
for(i=n1;i<=n2;i++)
56+
{
57+
sum = i ;
58+
while(sum>1)
59+
{
60+
sum = sqsum(sum);
61+
if (sum == 4)
62+
break;
63+
64+
}
65+
if (sum==1)
66+
printf("%d ",i);
67+
}
68+
break;
69+
case 3 :
70+
printf("Enter the number : ");
71+
scanf("%d",&num);
72+
sum = num ;
73+
while(sum>1)
74+
{
75+
sum = psqsum(sum);
76+
if (sum == 4)
77+
break;
78+
79+
}
80+
if (sum==1)
81+
printf("\n%d is Happy number",num);
82+
if (sum==4)
83+
printf("\n%d is Unhappy number",num );
84+
default :
85+
printf("Wrong choice!!!..... Please try again");
86+
break;
87+
}
88+
89+
90+
return 0;
91+
}
92+
93+

0 commit comments

Comments
 (0)