[Solved] Find next Aloha Number


Despite my comment above, I wondered about the “time and space complexity”. It turned out to be trivial; this only takes 3 long integer variables and a single loop over each input digit (which can be incremented by this algorithm to use 1 more digit; and this will not cause an integer overflow).

Starting from the lowest digit, if it’s lower than 4 replace it with 4. If it’s lower than 7, replace it with 7. For 8 and 9, replace it with 4 and increment the next digit. Repeat until all digits are processed.

The following code returns the number itself for a proper “aloha” number, the next higher if not.

It requires long variables (using more than 32 bits), because the aloha number for the largest allowed input, 2*(10^9), is 4444444444 — outside the range of a 32-bit integer.

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

int main (int argc, char **argv)
{
    long not_aloha, aloha, digit;
    if (argc != 2)
    {
        printf ("please give an aloha number\n");
        return -1;
    }
    not_aloha = atoi (argv[1]);
    printf ("not aloha: %ld\n", not_aloha);

    aloha = 0;
    digit = 1;
    while (not_aloha)
    {
        if ( (not_aloha % 10) <= 4)
            aloha += 4*digit;
        else if ( (not_aloha % 10 ) <= 7)
            aloha += 7*digit;
        else
        {
            aloha += 4*digit;
            not_aloha += 10;
        }
        digit *= 10;
        not_aloha /= 10;
    }
    printf ("aloha: %ld\n", aloha);

    return 0;
}

1

solved Find next Aloha Number