jjcastil
jjcastil

Reputation: 199

Determine if all the elements of array are prime numbers

I'm trying to write a java programme which determines if all the elements of an array are prime numbers. Here is my code:

boolean allPrimes(int[] ade){
        int i = 0; //counter
        boolean Prime = true; //initial boolean value
        while (i<ade.length && !Prime){
            if (p.isPrime(ade[i])) //function which determines if an int is prime.
                Prime = true;
            else
                Prime = false;
            i=i+1;
            }
        return Prime;
    }

I don't think this is correct as I've made some tests and they fail. What am I doing wrong? thanks

Upvotes: 1

Views: 2390

Answers (6)

Johnbabu Koppolu
Johnbabu Koppolu

Reputation: 3252

You initialized the boolean Prime like this

 boolean Prime = true;

That means you never enter while the loop! Initialize it to 'false' instead. Your assignments inside if also are misplaced.

For your code to work - Simply change your second condition in while from

while (i<ade.length && !Prime)

to

while (i<ade.length && Prime)

Upvotes: 4

TheOx
TheOx

Reputation: 2228

I'm not a Java guy but it seems to me your initial value for Prime should be false, not true, otherwise you'll never enter your while loop.

Upvotes: 1

Mike Lentini
Mike Lentini

Reputation: 1358

Building on what johnbk said:

boolean allPrimes(int[] ade){
        int i = 0; //counter
        boolean Prime = true; //initial boolean value
        while (i<ade.length){
            if (!p.isPrime(ade[i])) { //function which determines if an int is prime.
                Prime = false;
                break;
            }
            i=i+1;
        }
        return Prime;
}

That should work fine. Loop through the array, when you find a number that is not prime, set Prime to false and break out of the loop.

Upvotes: 1

Vala
Vala

Reputation: 5674

Don't store the value in a variable at all. Do the loop and return false on the first non prime value you find (they can't all be primes if you've found one that isn't, no point processing any further), then return true after the loop (if you get there, they're all primes).

for (int i : ade) {
    if (!p.isPrime(i)) {
        return false;
    }
}
return true;

Upvotes: 2

Nasreddine
Nasreddine

Reputation: 37848

You will never enter the while loop since Prime = true; and you're checking for while(i<ade.length && !Prime) which means while (true && false) (assuming ade will have some values in it)

Upvotes: 0

mishadoff
mishadoff

Reputation: 10789

Your Prime variable initializes to true and in while condition !Prime means false. Your while loop not executes and evaulates line return true.

Upvotes: 1

Related Questions