0

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?

2
  • 3
    Please fix your indentation. Commented Mar 25, 2014 at 18:12
  • 1
    temp.equals(twoPowern(x, y/2)): Why are you calling equals() here and not doing anything with the result? Commented Mar 25, 2014 at 18:14

3 Answers 3

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

@Simon what's the mistake in the function??
NO you'r right it works. There is a MUCH simpler way, however.
1
temp.equals(twoPowern(x, y/2));

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.