aspose file tools*
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
JavaRanch » Java Forums » Java » Java in General
Bookmark "Writing a recursive emthod using BigInteger" Watch "Writing a recursive emthod using BigInteger" New topic
Author

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?
[CODE]
import java.io.*;
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;
else
return (n.add(computeSum(n.subtract(base))) );
}
public static String getString() throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
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
Greenhorn

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:

mavedrive;
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Writing a recursive emthod using BigInteger