2014-03-25 77 views
0

我想找出2的權力n。我用這個遞歸函數。遞歸函數不工作java

我的代碼:

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(); 
} 
} 

但我沒有得到需要的結果。

例如1 2 3 4 5我得到2 1 2 1 2。 'C'中的一個類似的程序(使用類似的功能,但使用int)很好。

任何人都可以解釋什麼是錯誤?

+3

請修復您的縮進。 – bblincoe

+1

'temp.equals(twoPowern(x,y/2))':爲什麼你在這裏調用'equals()'而沒有對結果做任何事情? –

回答

4

我認爲你需要分配遞歸的結果,而不是測試是否相等:

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

應該

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

@Simon函數中有什麼錯誤? – nomorequestions

+0

不,你是對的。然而,有一種更簡單的方法。 – Simon

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

是Java中的條件語句,而不是分配,所以你不是 存儲的遞歸值。

0

這是很多簡單:

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)); 
     } 
    } 
} 

使用正則多頭或BigInteger的。