nomorequestions
nomorequestions

Reputation: 589

Recursive function not working java

I am trying to find out 2 to the power n. I used recursive function for this.

My Code:

class TwoPowerN
{
  static BigInteger twoPowern(BigInteger x, long y)
  {
    BigInteger temp = new BigInteger("1");
    if( y == 0)
      return new BigInteger("1");
    temp.equals(twoPowern(x, y/2));
    if (y%2 == 0)
      return temp.multiply(temp);
    else
      return x.multiply(temp.multiply(temp));
  }

public static void main(String args[]) throws IOException
{
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
  int t = Integer.parseInt(br.readLine());
  while(t>0)
  {
    long r = Long.parseLong(br.readLine());
    BigInteger a = new BigInteger("2");
    BigInteger ans=twoPowern(a,r);
    pw.println(ans);
    t--;
   }
  pw.close();
}
}

But I don't get the required result.

For cases 1 2 3 4 5 I am getting 2 1 2 1 2. A similar program(using similar function but with int) in 'C' works fine.

Can anyone explain what is the mistake?

Upvotes: 0

Views: 125

Answers (3)

Simon
Simon

Reputation: 2960

This is a lot simpler:

public class power2 {

    public static long power2( int power)
    {
        if(power <= 0)
            return 1;
        return 2 * power2(power-1);
    }

    static BigInteger twoPowern(long y)
    {
        if( y == 0) {
            return BigInteger.ONE;
        }

        return new BigInteger("2").multiply(twoPowern(y-1));
    }  

    public static void main(String[] args)
    {
        for(int i = 0; i < 10; i++)
        {
            System.out.println("2^" + i + "," + power2(i));
            System.out.println("2^" + i + "," + twoPowern(i));
        }
    }
}

Using regular longs, or BigInteger.

Upvotes: 0

jeffrey_t_b
jeffrey_t_b

Reputation: 1769

I think that you need to assign the recursive result, rather than test for equality:

temp.equals(twoPowern(x, y/2)); // This is checking for equality

Should be

temp = twoPowern(x, y/2); // This is assigning the value

Upvotes: 4

azurefrog
azurefrog

Reputation: 10955

temp.equals(twoPowern(x, y/2));

is a conditional statement in java, not an assignment, so you aren't storing the recursive value.

Upvotes: 1

Related Questions