Sicily 1203. The Cubic End(數論乘法)

題目大意:立方求尾數。求一個數的立方尾數等於本身。

解題思路:

1.判斷尾數相同,不需要將整個數乘完再取尾數。只要從低位開始,一位一位逐個匹配即可。

2.尾數爲1,3,7,9時,1立方尾數爲1,3立方尾數爲7,7立方尾數爲3,9立方尾數爲9。

所以,最後一位只有相應4種可能。

3.取尾數操作即求模,取最後一位即模10,最後兩位模10^2。

4.在立方取模時運用到數論乘法求模。

a^3 % m = (((a * a) % m) * a) % m

因爲a<m,所以先進行a*a再求模。利用公式減小數值範圍。

5.但在大於等於10位時,long long也會溢出。所以運用到數論中的乘法求模,在乘法過程中不斷求模。

相關介紹:點擊打開鏈接


// 1203. The Cubic End(快速乘法) 

#include <cstdio>
#include <cmath>
#include <cstring>
  
using namespace std;  

long long mul(long long a, long long b, long long mod) {
    long long c = 0;
    const int base = 2;
    for (; b != 0; b /= base) {
        c += (b % base) * a;
        c %= mod;
        a = (a * base) % mod;
    }
    return c;
}

long long cube(long long x, long long mod){
    return mul(mul(x,x,mod), x, mod);    
}

int main () {
    //freopen("D:\\input.txt","r",stdin);
    int t, length;
    long long result, remain, power, step;
    char str[11];
    
    scanf("%d",&t);
    while( t-- ){
        scanf("%s",&str);
        length = strlen(str);
        result = remain = str[length-1] - '0';
        power = 10;
        
        if( result == 3 ) result = 7;
        else if( result == 7 ) result = 3;
        
        for( int i = length - 2; i >= 0; --i ){
            remain += (str[i] - '0') * power;
            step = power;
            power *= 10;            
            while( cube(result,power) != remain ){
                result += step;    
            }    
        }
        printf("%lld\n",result);
    }
 
    return 0;  
}  


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章