Mario Milovanovic Mario Milovanovic - 1 month ago 14
C Question

Find the largest interesting number smaller than a given integer

One number is interesting if it's flipped number is divisible by the number of digits it contains. So the program should read from SI an ingeter n(n>9).
Find and print the largest interesting number smaller than n. If the input number is invalid it should print "Invalid input".
So this is the code I've written but I can't get it to work.
I kindly ask for some help.
Thanks in advance

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

int main()
{
int n, flippedNumber=0, remainder;
int count = 0, i;
scanf ("%d", &n);
int largestInteresting = n;
while ( n != 0)
{
n /= 10;
++count;
}
while (n > 9)
{
for (i = 0; i < n; i++)
{
remainder = n%10;
flippedNumber = flippedNumber*10 + remainder;
n /= 10;
}
--largestInteresting;
}
if ((flippedNumber % count) == 0 && largestInteresting > i)
printf ("%d", largestInteresting);
else
printf ("Invalid input");
return 0;
}

Answer

Issues with your code: you effectively destroy n doing the digit count but then try to reuse it for something else without refreshing its value (form largestInteresting?); you don't do the interesting number check in a loop that counts down on the input number so you never find what you're looking for; you wait until the loops are complete before doing the interesting number test, but you don't need to complete the loops once you find the first interesting number if you're counting down.

My rework below incorporates my twisted explanation above as well as some style tweaks:

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

int main()
{
    int number;

    (void) scanf ("%d", &number);

    if (number < 10)
    {
        fprintf(stderr, "Invalid input\n");
        return EXIT_FAILURE;
    }

    for (int n = number; n > 9; n--)
    {
        int digitCount = 0;
        int temporary = n;

        while (temporary != 0)
        {
            temporary /= 10;
            ++digitCount;
        }

        int flippedNumber = 0;
        temporary = n;

        for (int i = 0; i < digitCount; i++)
        {
            int remainder = temporary % 10;
            flippedNumber = flippedNumber * 10 + remainder;
            temporary /= 10;
        }

        if ((flippedNumber % digitCount) == 0)
        {
            printf("%d\n", n);
            return EXIT_SUCCESS;
        }
    }

    fprintf(stderr, "No interesting numbers found!\n");     
    return EXIT_FAILURE;
}

EXAMPLE USAGE

> echo 10 | ./a.out
No interesting numbers found!
> echo 100 | ./a.out
89
> echo 1000 | ./a.out
999
> echo 10000 | ./a.out
8899
> echo 100000 | ./a.out
59999
> echo 1000000 | ./a.out
899997
>