zoukankan      html  css  js  c++  java
  • HDU 1097 A hard puzzle(快速幂)

    Problem Description
    lcy gives a hard puzzle to feng5166,lwg,JGShining and Ignatius: gave a and b,how to know the a^b.everybody objects to this BT problem,so lcy makes the problem easier than begin.
    this puzzle describes that: gave a and b,how to know the a^b's the last digit number.But everybody is too lazy to slove this problem,so they remit to you who is wise.
     
    Input
    There are mutiple test cases. Each test cases consists of two numbers a and b(0<a,b<=2^30)
     
    Output
    For each test case, you should output the a^b's last digit number.
     
    Sample Input
    7 66
    8 800
     
    Sample Output
    9 6
     
    一开始这道题,就想,乘法取模嘛,然后超时,然后想起还有一直东西叫快速幂的(觉得百度百科写的挺详细的,当时就是从那里学的)
     1 #include<cstdio>
     2 int mod(int a,int b){
     3     int ans=1;
     4     a=a%10;
     5     while(b>0){
     6         if(b&1) //如果b是基数,位运算 
     7             ans=(ans*a)%10;
     8         b>>=1;//b/2 
     9         a=(a*a)%10;
    10     }
    11     return ans;
    12 }
    13 int main(){
    14     int a,b;
    15     while(scanf("%d%d",&a,&b)==2)
    16         printf("%d
    ",mod(a,b));
    17     return 0;
    18 }

    然后看别人的代码,发现还有一种,找规律

    0,1,5,6的任意次循环,它的尾数都是它本身

    2循环为:2,4,8,6

    3循环为:3,9,7,1

    4循环为:4,6

    7循环为:7,9,3,1

    8循环为:8,4,2,6

    9循环为:9,1

    当然你可以直接就用数组输出,你也可以把每一个数都当成有4次循环

     1 #include<stdio.h>
     2 int main()
     3 {    int a,b,c[4]; 
     4   while(scanf("%d%d",&a,&b)!=EOF)  
     5   {     
     6       a=a%10;
     7       c[0]=a;//一次
     8      c[1]=(c[0]*a)%10;//二次
     9      c[2]=(c[1]*a)%10;//三次
    10      c[3]=(c[2]*a)%10;//四次    
    11      if(b%4==1)        
    12         printf("%d",c[0]);
    13      if(b%4==2)    
    14         printf("%d",c[1]);
    15      if(b%4==3)         
    16         printf("%d",c[2]);
    17      if(b%4==0)         
    18         printf("%d",c[3]);
    19     printf("
    ");
    20   }    
    21   return 0;
    22 }
  • 相关阅读:
    Vue基础
    ES6之promise
    第13次作业--邮箱的正则表达式
    第12次作业--你的生日
    第11次作业--字符串处理
    第10次作业
    Java找回感觉的练习
    第四次博客作业-结对项目
    第9次作业--接口及接口回调
    深入面向对象——继承
  • 原文地址:https://www.cnblogs.com/cake-lover-77/p/10197890.html
Copyright © 2011-2022 走看看