Monday, May 25, 2015

Porcupine Number (MUM Sample Questions)

A Prime number is an integer that is divisible only by 1 and itself. A porcupine number is a prime number whose last digit is 9 and the next prime number that follows it also ends with the digit 9. For example 139 is a porcupine number because:

a. it is prime
b. it ends in a 9
c. The next prime number after it is 149 which also ends in 9. Note that 140, 141, 142, 143, 144, 145, 146, 147 and 148 are not prime so 149 is the next prime number after 139.

Write a method named findPorcupineNumber which takes an integer argument n and returns the first porcupine number that is greater than n. So findPorcupineNumber(0) would return 139 (because 139 happens to be the first porcupine number) and so would findPorcupineNumber(138). But findPorcupineNumber(139) would return 409 which is the second porcupine number.

Solution::

public static int findPorcupineNumber(int n){
        int sycoNum = n;
        boolean yuppie = true;

        while(yuppie){
            sycoNum++; 
            
            if(isPrime(sycoNum)){
                int temp1 = sycoNum; 
                boolean nxtPrimeFound = true;
                
                while(nxtPrimeFound){
                    temp1++;
                    if(isPrime(temp1)) nxtPrimeFound = false;
                }

                if((sycoNum % 10) == 9 && (temp1 % 10)== 9){
                    System.out.println("Porcupine Number = " + sycoNum);
                    yuppie = false;
                }
            }
        }
     }
}

-by Yubraj Pokharel :)

5 comments: