-3

The input line contains three positive integers: r, s, and a, where (2 <= r < s < a). It is guaranteed that r is prime.

It should print YES, if s is the next prime number after r and a is the next prime number after s; otherwise, it should print NO.

Currently, I have the following isPrime() method:

boolean isPrime(int n)  {
    //check if n is a multiple of 2
    if (n%2==0) 
        return false;
    //if not, then just check the odds
    for(int i=3;i*i<=n;i+=2) {
        if(n%i==0)
            return false;
    }
    return true; 
}
asteri
  • 11,402
  • 13
  • 60
  • 84
Pritish
  • 769
  • 4
  • 13
  • 28
  • 7
    What have you tried as for the consecutive requirement? We're not doing your homework if you haven't tried that. – nanofarad Aug 01 '13 at 17:52
  • That is piece I am confused about.. And need help on. Any pointers will be appreciated – Pritish Aug 01 '13 at 17:54
  • 1
    Are they all prime? Are any numbers in between them prime? – Geobits Aug 01 '13 at 17:54
  • 4
    Also, your isPrime method says 2 is composite... – StephenTG Aug 01 '13 at 17:54
  • 2
    Trivial (suboptimal solution): 1. are all three prime. 2. loop across r-s and s-a, checking for primes there. If the first succeeds (yes three primes), and the second two fail (no, no other primes), then you have success. Otherwise, fail. – zebediah49 Aug 01 '13 at 17:55
  • I need to return YES if they are all prime..NO otherwise – Pritish Aug 01 '13 at 17:55
  • I think these must be sufficient enough http://stackoverflow.com/questions/4475996/given-prime-number-n-compute-the-next-prime http://stackoverflow.com/questions/2468412/finding-a-prime-number-after-a-given-number – Algorithmist Aug 01 '13 at 17:59

2 Answers2

1

Try this:

public int nextPrime(int start){
    int next = start+1;

    while(!isPrime(next)){
        next++;
    }

    return next;
}

public void arePrimeSequence(int r, int s, int a){
    int firstPrime = nextPrime(r);
    int secondPrime = nextPrime(firstPrime);

    if(s == firstPrime && a == secondPrime){
        System.out.println("YES");
    }
    else{
        System.out.println("NO");
    }
}
NinjaBlob
  • 111
  • 6
0

Some improvement can be made in the code to determine next prime. Instead of incrementing by 1 you can increment the number by 2. As first number is guaranteed as prime and if it is not 2 then increment by 2.

public int nextPrime(int start){

if (start==2) return 3;
int next = start+2;

while(!isPrime(next)){
    next+=2;
}

return next;

}

Prabir Ghosh
  • 430
  • 3
  • 7