-2

My code for checking if a number is prime is below. I am passing through a huge number, that is why I am using BigDecimal.

BigDecimal n = new BigDecimal("29331922499794985782735976045591164936683059380558950386560160105740343201513369939006307531165922708949619162698623675349030430859547825708994708321803705309459438099340427770580064400911431856656901982789948285309956111848686906152664473350940486507451771223435835260168971210087470894448460745593956840586530527915802541450092946574694809584880896601317519794442862977471129319781313161842056501715040555964011899589002863730868679527184420789010551475067862907739054966183120621407246398518098981106431219207697870293412176440482900183550467375190239898455201170831410460483829448603477361305838743852756938687673");
    //n is not prime

I send all of the "supposed" prime numbers to an ArrayList which I will use to calculate something else later on in the future. This runs through fairly quickly, but it errors out after nearly 100 trials. I was wondering if anyone could help me with fixing this code.

 /**
 * 6a - 1 = prime number
 * a = (prime number + 1)/6
 */
public static void isPrime(BigDecimal n)
{
    BigDecimal six = new BigDecimal("6");
    BigDecimal que = (n.add(one)).remainder(six); //Highlights this spot and says StackOverFlow - null (in java.math.MutableBigInteger)
    if(count == 0)
    {
        System.out.println("True/False: N is prime. " + que.equals(zero) + ", the remainder is " + que); //By the way, this says that the original number is non-prime.
    }
    else
    {
        if(que.equals(zero))
        {
            System.out.println("The number, " + n + " is prime!");
            p.add(n);
        }
    }
    count++;
    if(n.compareTo(one)== 1)
        isPrime(n.subtract(one));
}
President James K. Polk
  • 40,516
  • 21
  • 95
  • 125
xXMavhawkXx
  • 37
  • 1
  • 9

1 Answers1

0

Try to avoid recursion. Because of limit on stack you will get exception. Or, you can increase Stacksize for JVM:

Stack overflows from deep recursion in Java?

For more detailed answer provide a minimal reproducible example.

Woland
  • 623
  • 2
  • 13
  • 31