Randy Huang Randy Huang - 2 months ago 12
Java Question

java finding primes that have digits that add to a multiple of 10 in a range

I'm writing a piece of code that finds primes that have digits that sum up to a multiple of ten, from

start
to
end
, but I'm having a hard time finding the mistake in my code that is finding them and other unessescary primes that don't sum to a multiple of ten.

void funPrimes(int start, int end) {
int ten = 0;
for (int n = start; n < end; n++){
int current = n;
while (current > 0){
ten += current%10;
current=current/10;
}
if(isPrime(n)&&ten%10==0) println(n);
}
}
boolean isPrime(int num){
boolean p = true;
for(int i = 2; i < num; i++){
if(num%i ==0) return false;
}
return p;
}


For example, if
start = 1
and
end = 2048
, then the only numbers that should be printed out are 19, 37, 73, 127, 163, 181, 271...

But when I run my code, the numbers that come up are 19, 47, 59, 71, 79, 103, 139, 179, 199...

Answer

The problem is you do not reset the variable ten every time you loop. This works:

void funPrimes(int start, int end) {
    int ten = 0;
    for (int n = start; n < end; n++) {
        ten = 0;
        int current = n;
        while (current > 0) {
            ten += current % 10;
            current = current / 10;
        }
        if (isPrime(n) && ten % 10 == 0) {
            System.out.println(n);
        }
    }
}

In my opinion it makes the code much cleaner if you also break the function to determine if a number is divisible by 10 into its own method:

void funPrimes(int start, int end) {
    for (int n = start; n < end; n++) {
        if (isPrime(n) && digitsAddToTen(n)) {
            System.out.println(n);
        }
    }
}

boolean isPrime(int num) {
    boolean p = true;
    for (int i = 2; i < num; i++) {
        if (num % i == 0) {
            return false;
        }
    }
    return p;
}

boolean digitsAddToTen(int num) {
    int digitTotal = 0;
    while (num > 0) {
        digitTotal += num % 10;
        num = num / 10;
    }
    return (digitTotal % 10 == 0);
}