This week's book giveaway is in the Other Languages forum.
We're giving away four copies of Functional Reactive Programming and have Stephen Blackheath and Anthony Jones on-line!
See this thread for details.
Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Writing a recursive emthod using BigInteger

 
Gerald Spica
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



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;
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic