Geometric Progression using Recursion (Java)

766 views java
3

I have an assignment for class where I need to write a method which calculates a Geometric progression for n integers using recursion.

The value of n is received from the user.

public static float Geometric(float n)
{
    if(n==0)
        return 1;
    else 
    {
        if(n == 1)
            System.out.println(n); 
        else    
            return (n * Geometric(n-1)); 
    }
}

The code works fine, until the value of n exceeds 34. Then, the method starts returning wrong answers. I'm assuming it has to do with the maximum value that a float can hold.

Is there a way to calculate/store values that exceed the maximum value of the primitive data types?

It seems to me that recursion isn't a good way to calculate a geometric progression, but maybe I'm just missing something. Any suggestions?

Thanks!

answered question

Have you any idea about tail recursion ?

double will hold more than float.. or use long if you only need integers and not decimal numbers

what is the common ratio and first term og geometric progression ?

1 Answer

5

Welcome to StackOverflow!

For dealing with massive numbers, you can try looking at BigDecimal or BigInteger class. There is also another StackOverflow question (Finding the factorial using recursion with the BigInteger Class) that should be quite similar to your case

posted this

Have an answer?

JD

Please login first before posting an answer.

Ads

Categories