2017-07-16 32 views
1

我有一個問題,我不得不計算一個數組的大冪數的和,並返回結果。例如arr = [10,12,34,56],那麼輸出應該是 10^1 + 12^2 + 34^3 + 56^4。這裏的輸出可能非常大,所以我們被要求在輸出中取一個10^10 + 11的模,然後返回它。蟒蛇,但在Java最初我使用BigInteger,並得到了一半的測試用例,所以我想用龍,然後用模塊指數計算功耗,但然後我得到了錯誤的輸出是精確的所有負面,因爲它顯然超出了極限。沒有使用大整數的大冪

這是我的代碼使用長和模塊指數。

static long power(long x, long y, long p) 
{ 
    long res = 1;  // Initialize result 

    x = x % p; // Update x if it is more than or 
       // equal to p 

    while (y > 0) 
    { 
     // If y is odd, multiply x with result 
     if ((y & 1)==1) 
      res = (res*x) % p; 

     // y must be even now 
     y = y>>1; // y = y/2 
     x = (x*x) % p; 
    } 
    return res; 
} 

static long solve(int[] a) { 
    // Write your code here 
    Long[] arr = new Long[a.length]; 

    for (int i = 0; i < a.length; i++) { 
     arr[i] = setBits(new Long(a[i])); 
    } 
    Long Mod = new Long("10000000011"); 
    Long c = new Long(0); 
    for (int i = 0; i < arr.length; i++) { 
     c += power(arr[i], new Long(i + 1),Mod) % Mod; 
    } 

    return c % Mod; 
} 

static long setBits(Long a) { 
    Long count = new Long(0); 
    while (a > 0) { 
     a &= (a - 1); 
     count++; 
    } 
    return count; 
} 

然後我也嘗試二進制冪,但沒有工作了me.How做我做到這一點,而無需使用大的整數,那樣容易,因爲我在Python

+0

BigInteger究竟是如何失敗的?因爲使用這個庫是最容易編碼的解決方案嗎? – GhostCat

+0

@GhostCat我得到了一半的測試用例 – ani

+0

你正在重複你已經說過的。 Tle是什麼意思?但想一想:你是對的 - 你應該專注於獲得模數解決方案。用較小的數字進行計算總是更高效。 – GhostCat

回答

0

您已經添加了一個額外的零價值得到了它mod,應該是100000011. 希望這能解決它

+0

不,它沒有...我仍然得到錯誤的答案 – ani

+0

分享鏈接到問題 – neilharia7