RyeHumor
RyeHumor

Reputation: 11

Java Recursion and super prime numbers

This method is intended to recursively go through the method and tell if a number is "super Prime". A super prime number is a number that is prime itself and each time it is diveded by 10 all of those numbers are prime as well. for example 2333 is super prime because 233 is prime 23 is prime and 2 is prime. My method keeps returning false even though i pass in the number 2333. the isPrime() method successfully tests if a number is prime.

public boolean isSuperPrime(int h)
{
    if((h<10)&&isPrime(h))
        return true;
    else if(isPrime(h))
        return isSuperPrime(h/10);  
    else
        return false;


}

Upvotes: 1

Views: 4273

Answers (1)

Kevin DiTraglia
Kevin DiTraglia

Reputation: 26068

I suspect your isPrime method is incorrect, I ran this exact code:

public static void main(String []args)
{
   System.out.println(isSuperPrime(2333));
}

public static boolean isSuperPrime(int h)
{
    if ((h<10)&&isPrime(h))
        return true;
    else if (isPrime(h))
        return isSuperPrime(h/10);  
    else
        return false;
}

//Note this is not an efficient implementation, 
//but it is correct, was just using it to test
public static boolean isPrime(int n)
{
    for(int i=2;i<n;i++) {
        if(n%i==0)
             return false;
    }
    return true;
}

and it returns true.

Upvotes: 4

Related Questions