This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
The moose likes Java in General and the fly likes Writing a recursive emthod using BigInteger Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Writing a recursive emthod using BigInteger" Watch "Writing a recursive emthod using BigInteger" New topic

Writing a recursive emthod using BigInteger

Gerald Spica
Ranch Hand

Joined: Jul 28, 2003
Posts: 30
I am trying to express the Recursive method

using BigInteger instead of int, when I run the code below it compiles but I get an error on line 35

Line 35 from the code below is,

from what I am able to discern from the java.math.BigInteger class this is
how this method should be declared. Can anyone help?
import java.math.BigInteger;

class ComputeSumApp
static int aNumber;
static int x = 1;
static BigInteger base = BigInteger.valueOf (x);

public static void main(String[] args) throws IOException
System.out.println("Enter a number: ");
aNumber = getInt();
BigInteger number = BigInteger.valueOf (aNumber);
BigInteger answer = computeSum(number);
System.out.println("Sum of the first N postitive BigInteger = " + answer);
public static BigInteger computeSum(BigInteger n)
if (n==base)
return base;
return (n.add(computeSum(n.subtract(base))) );
public static String getString() throws IOException
InputStreamReader isr = new InputStreamReader(;
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
public static int getInt() throws IOException
String s = getString();
return Integer.parseInt(s);

Maverick Lasa

Joined: Oct 18, 2003
Posts: 23

Hello Gerald,
The condition n==base compares the reference of the BigInteger instances and NOT their values, thus this condition is always FALSE as base and n refers to a different instances.
Try the following:

I agree. Here's the link:
subject: Writing a recursive emthod using BigInteger
It's not a secret anymore!