How to implement the BigInteger class for your own equation?

I have an equation that I need to write in BigInteger format. It should be in a for loop. This is what I have so far, but I don’t know how to use BigInteger. This is the equation written in the for loop: i * (i + 1) * (2 * i + 1) * (3 * i * i + 3 * i-1) / 30

public static BigInteger[] nthtetranum(int n) //This is the method using the simple formula for tetra number.
{

    BigInteger[] nth = new BigInteger[n];

    for(int i = 0; i <nth.length; i++)
    {
        //nth[i] = i*(i+1)*(2*i+1)*(3*i*i+3*i-1)/30;
        nth[i] = 

    }
    return nth;
+3
source share
2 answers
BigInteger two = new BigInteger("2");
BigInteger three = new BigInteger("3");
BigInteger I = new BigInteger(""+i); // "I" is a bigint version of "i"
nth[i] = I
    .multiply(I.add(BigInteger.ONE))
    .multiply(I.multiply(two).add(BigInteger.ONE))
    .multiply(I.multiply(I).multiply(three).add(I.multiply(three)).subtract(BigInteger.ONE))
    .divide(new BigInteger("30"));

This expression is ugly, but it will not overflow even for "borderline" values i.

+2
source

Um. The usual way?

nth[i] = BigInteger.valueOf(i)
  .multiply(BigInteger.valueOf(i+1))
  .multiply(BigInteger.valueOf(2*i + 1))
  .multiply(BigInteger.valueOf(3L*i*i + 3*i - 1)) // should fit in a long
  .divide(BigInteger.valueOf(30));
0
source

All Articles