Randy Huang - 22 days ago 4x

Java Question

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

`start`

`end`

`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`

`end = 2048`

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);
}
```

Source (Stackoverflow)

Comments