javageometric-mean

How to calculate the sum of geometric series


I want to calculate the sum of a geometric series. ie: 1 , 5 , 25 , 125 , etc I try to use the math formula to calculate it: a(r^n -1)/(r-1)

My code:

int a = 1;
int r = 5;
int deno = r -1;
int n = 3
int rn = r^n -1 ;

int total = a * rn / deno;

Apparently there is wrong with the code and only some values like the example I give works. I do not know why QAQ

I think the problem is the symbol ^ can anyone explain what ^ does in java? Appreciate it


Solution

  • Atleast in Java 7, the symbol ^ does not mean power.

    Try this, you would also like to put a condition where r>1 or r<1. Both have different formuals.

            int a = 1;
            int r = 5;
            int deno = r -1;
            int n = 3;
            double sum=a*(Math.pow(r, n)-1)/deno;