-4

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; 
}
7
  • 7
    What have you tried as for the consecutive requirement? We're not doing your homework if you haven't tried that. Commented Aug 1, 2013 at 17:52
  • That is piece I am confused about.. And need help on. Any pointers will be appreciated Commented Aug 1, 2013 at 17:54
  • 1
    Are they all prime? Are any numbers in between them prime? Commented Aug 1, 2013 at 17:54
  • 4
    Also, your isPrime method says 2 is composite... Commented Aug 1, 2013 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. Commented Aug 1, 2013 at 17:55

2 Answers 2

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");
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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;

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.