Find the multiple fulgaps

Asked

Viewed 48 times

1

The goal of the program is to show only the numbers fulgaps from 0 to 999, this number must be divisible by concatenating the first and last number Ex: 192 / 12 or 583 / 53.

In the compilation is shown all numbers from 1 to 999 and not only the desired numbers. Can anyone tell me what the error of my logic?

#include <iostream>

int main()
{
    int Number{ 1 };
    int FirstLastNumber = ((Number / 100) * 10) + Number % 10;
    int Result = Number % FirstLastNumber;

    for (int i = 0; i <= 999; i++)
    {
        if (Result == 0)
        {
            std::cout << Number << std::endl;
            Number++;
        }
    }
    return 0;
}
  • 1

    Do you understand that the answer you accepted does not do what is in the statement of the question?

2 answers

1


First you need to redo the account of Result for each new implementation of for. The way it is currently done does not occur, in this situation you get only once a value for Result.

int FirstLastNumber = ((Number / 100) * 10) + Number % 10;

In this line you need to differentiate if the number is 3 digits or only 2, because the calculation is different. Since it is 3 digits the calculation of the rest at the end of the equation should be Number%100 and not Number%10 as it is currently.

Follow an example from 100 to 999 based on your code:

#include <iostream>

int main()
{
    int Number{ 100 };
    int FirstLastNumber;
    int Result;

    for (int i = 100; i <= 999; i++)
    {
        FirstLastNumber = ((Number / 100) * 10) + ((Number % 100) % 10);
        Result = Number % FirstLastNumber;
        if (Result == 0)
        {
            std::cout << Number << std::endl;
        }
        Number++;
    }
    return 0;
}

1

The problem is a little ambiguous. And the code has a lot of nonsense. The main mistake is to calculate outside the loop.

Nothing was said about what to do when the number has only 2 digits and not 1. I will consider that the first one is 0. So I calculate only the last digit in these cases.

#include <iostream>

int main() {
    for (int i = 0; i < 1000; i++) {
        int FirstLastNumber;
        if (i < 100) FirstLastNumber = i % 10;
        else FirstLastNumber = ((i / 100) * 10) + i % 10;
        if (FirstLastNumber == 0 || i % FirstLastNumber == 0) std::cout << i << std::endl;
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Thank you very much, I will pay more attention to these details and try to be more specific next time.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.