HDU 1061 Rightmost Digit

l         Problem-solving ideas:

做这个题首先要知道两个数学规律:

//任何两个数相乘的最低位一定是它们最低位相乘所得结果的最低位

//同一个数连乘结果是具有周期性的,周期不大于10

方法一:利用以上两个规律构造出乘积周期性的解法。

方法二:直接利用快速幂

l         Source code:

方法一:

#include<stdio.h>

#include<math.h>

 

int main()

{

       int ncase;

       int a,t,rst,k,m;

       int record[10];

       int i;

       

       scanf("%d",&ncase);

       while(ncase--)

       {

              scanf("%d",&a);

              k=a%10;

              t=k;

              record[0]=t;

              for(i=1;i<10;i++)

              {

                     t=(k*t)%10;

                     record[i]=t;

                     if(k == t)

                     {

                            m=i;

                            break;

                     }

              }

 

              printf("%d\n",record[(a-1)%m]);

       }

       return 0;

}

 

方法二:

#include<stdio.h>

 

int pow(int x, unsigned int n)

{

    int rst = 1;

while (n > 0)

{

        if (n & 1)        // n & 1等价于(n % 2) == 1

            rst = (rst*x)%10;

        x = (x*x)%10;

        n >>= 1;        // n >>= 1等价于n /= 2

    }

   return rst;

}

 

int main()

{

       int ncase;

       int a;

 

       scanf("%d",&ncase);

       while(ncase--)

       {

              scanf("%d",&a);

 

              printf("%d\n",pow(a%10,a));

       }

       return 0;

}

你可能感兴趣的:(HDU 1061 Rightmost Digit)