How to extract digit and check whether it is prime digit or not in java?

Viewed 39

Does anyone know how to take a number, extract its digits and display the digits which are prime numbers? for ex - 762 Output: 7, 2

I have written the programmed till here:

 // program to input a number, print the prime digit, ex - 762 = 7,2
        int n, d, i=1, c=0;
        System.out.println("Enter a number");
        n = in.nextInt();
        while (n>0) {
            d = n%10;
            while (i<=d) {
                if (d%i==0) {
                    c++;
                }
                i++;
            }
            if (c==2) {
                System.out.println(d);
            }
            n = n/10;
        }

Output screenshot

I don't know why the loop is not repeating. If anyone knows, please help.

1 Answers

You need to reset i to 1 with each digit

    while (n>0) {
        d = n%10;
        i = 1;
        while (i<=d) {
            if (d%i==0) {
                c++;
            }
            i++;
        }
        if (c==2) {
            System.out.println(d);
        }
        n = n/10;
    }

BTW there are few enough prime numbers in the range to 1 - 9 that you could just manually code in checks for matching if digit is prime (not calculate for each digit)

Related