How to find all happy numbers in a specific range with C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>

/*
 A happy number is a number that eventually reaches 1 
 when repeatedly replaced by the sum of the squares of its digits.

 19 = 1^2 + 9^2 = 82
 19 -> 82 -> 68 -> 100 -> 1 eventually reaches 1 
 19 = happy number
*/

// Compute the sum of squares of digits of n
int sumOfDigitSquares(int n) {
    int sum = 0;
    while (n > 0) {
        int d = n % 10;
        sum += d * d;
        n /= 10;
    }
    return sum;
}

// Determine whether n is a happy number
int isHappy(int n) {
    int seen[1024];
    int seenCount = 0;

    while (n != 1) {
        // check if we've seen n before
        for (int i = 0; i < seenCount; i++) {
            if (seen[i] == n) {
                return 0; // cycle detected → not happy
            }
        }

        // record n
        if (seenCount < 1024) {
            seen[seenCount++] = n;
        }

        n = sumOfDigitSquares(n);
    }

    return 1; // n == 1 → happy
}

int main(void) {
    int a = 1, b = 100;

    if (a > b) {
        int temp = a;
        a = b;
        b = temp;
    }

    // dynamic array for happy numbers
    int capacity = 16;
    int size = 0;
    int *happyNumbers = malloc(capacity * sizeof(int));

    for (int i = a; i <= b; i++) {
        if (isHappy(i)) {
            if (size == capacity) {
                capacity *= 2;
                happyNumbers = realloc(happyNumbers, capacity * sizeof(int));
            }
            happyNumbers[size++] = i;
        }
    }

    printf("Happy numbers in range [%d, %d]:\n", a, b);
    for (int i = 0; i < size; i++) {
        printf("%d ", happyNumbers[i]);
    }
    printf("\n");

    free(happyNumbers);
    
    return 0;
}


/*
run:

Happy numbers in range [1, 100]:
1 7 10 13 19 23 28 31 32 44 49 68 70 79 82 86 91 94 97 100 

*/

 



answered Feb 24 by avibootz
...