Happy Number solution using c language--programming_info problem 24

Happy Number:




#include <stdio.h>    
     
//isHappyNumber() will determine whether a number is happy or not    
int isHappyNumber(int num){    
    int rem = 0, sum = 0;    
        
    //Calculates the sum of squares of digits    
    while(num > 0){    
        rem = num%10;    
        sum = sum + (rem*rem);    
        num = num/10;    
    }    
    return sum;    
}    
        
int main()    
{    
    int num = 82;    
    int result = num;    
        
    while(result != 1 && result != 4){    
        result = isHappyNumber(result);    
    }    
        
    //Happy number always ends with 1    
    if(result == 1)    
        printf("%d is a happy number", num);    
    //Unhappy number ends in a cycle of repeating numbers which contains 4    
    else if(result == 4)    
        printf("%d is not a happy number", num);     
     
    return 0;    
}
    Share:

    No comments:

    Post a Comment

    Translate

    Recommended platforms

    1. codechef
    2. hackerrank
    3. codeforces
    4. leetcode
    5. hackerearth

    Popular Posts

    programming_info. Powered by Blogger.

    Blog Archive

    Recent Posts

    other platforms

    • geeks for geeks
    • w3schools
    • codepen
    • skillshare
    • udemy

    Pages

    reader support Support