Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can check if the digits of a number are prime and if so multiply them in C

The problem says that the user will input numbers till he inserts 0 (exit) then if there are any prime digits in that given number, the program shall multiply them.

For example:
input : 4657
output : 35 ( 5 * 7 )

Here is what I have tried so far but I cannot pull it off with the multiplication… my code might look a little bit clumsy, I am a beginner 🙂

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

int main() {
    int number;
    int digit, prime;
    int i, aux;
    int multiplier;

  input:
    printf("Give Number :");
    scanf("%d", &number);
   
    do {
        multiplier = 1;
        digit = number % 10;
        number = number / 10;

        printf("%d \n", digit);

        prime = 1;
        for (i = 2; i <= sqrt(digit); i++) {
            if (digit % 1 == 0) {
                prime = 0;
            }
        }
        if (prime != 0) {
            multiplier = multiplier * digit;
        }
    } while (number != 0);

    printf("The result  : %d\n", multiplier);

    goto input;

    return 0;
}

>Solution :

There are multiple problems in your code:

  • missing #include <stdio.h>
  • use of label and goto statement to be avoided at this stage.
  • testing for prime digits can be done explicitly instead of a broken loop.
  • digit % 1 == 0 is always true, you should write digit % i == 0 (maybe a typo from copying someone else’s code?
  • i <= sqrt(digit) will not work unless you include <math.h> and still a bad idea. Use i * i < 10 instead.
  • 0 and 1 should not be considered primes.
  • it is unclear what the output should be if none of the digits are prime, let’s assume 1 is OK.

Here is a modified version:

#include <stdio.h>

int main() {
    for (;;) {
        int number, multiplier;

        printf("Give Number :");
        if (scanf("%d", &number) != 1 || number <= 0)
            break;
   
        multiplier = 1;
        while (number != 0) {
            int digit = number % 10;
            number = number / 10;
            if (digit == 2 || digit == 3 || digit == 5 || digit == 7)
                multiplier *= digit;
        }
        printf("The result: %d\n", multiplier);
    }
    return 0;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading