1. 程式人生 > >CH0101 a^b & CH0102 64位整數乘法

CH0101 a^b & CH0102 64位整數乘法

大數取模的兩道題。

虐狗寶典學習筆記:

兩個數值執行算術運算時,以參與運算的最高數值型別為基準,與儲存結果的變數型別無關。兩個32位整數的成績可能超過int型別的表示範圍,但是CPU只會用一個32位暫存器儲存結果,造成越界,此時我們必須把其中一個數強制轉換成64位整數型別long long參與運算。得到正確的結果,取模後,執行賦值操作時,該結果會被隱式轉換成int存回。

 

CH0101---a^b

 1 #include <bits/stdc++.h>
 2 #define inf 0x3f3f3f3f
 3 using namespace std;
 4 typedef long
long LL; 5 6 int power(int a, int b, int p) 7 { 8 int ans = 1 % p; 9 while(b){ 10 if(b & 1) ans = (long long) ans * a % p; 11 a = (long long)a * a % p; 12 b >>= 1; 13 } 14 return ans; 15 } 16 17 int main() 18 { 19 int a, b, p; 20 scanf("
%d%d%d", &a, &b, &p); 21 printf("%d\n", power(a, b, p)); 22 return 0; 23 }

 

CH0102---64位整數乘法

 1 #include <bits/stdc++.h>
 2 #define inf 0x3f3f3f3f
 3 using namespace std;
 4 typedef long long LL;
 5 
 6 long long mul(long long a, long long b, long long p)
 7 {
 8     long
long ans = 0; 9 while(b){ 10 if(b & 1) ans = (ans + a) % p; 11 a = a * 2 % p; 12 b >>= 1; 13 } 14 return ans; 15 } 16 17 int main() 18 { 19 LL a, b, p; 20 scanf("%lld%lld%lld", &a, &b, &p); 21 printf("%lld\n", mul(a, b, p)); 22 return 0; 23 }