zoukankan      html  css  js  c++  java
  • 快速求幂运算

     1 #include <stdio.h>
     2 #include <math.h>
     3 //递归算法
     4 int recursion(int a,int b)
     5 {
     6     int tem = 1;
     7     if(b==0)return 1;
     8     else if(b==1)return a;
     9     tem = recursion(a,b>>1);
    10     tem = tem*tem;
    11     if(b&1) tem = tem * a;
    12     return tem;
    13 }
    14 //循环算法
    15 int loop(int a,int b)
    16 {
    17     int tem=1,ret=a;
    18     while(b>0)
    19     {
    20         if(b&1) tem = tem * ret;
    21         ret = ret*ret;
    22         b>>=1;
    23     }
    24     return tem;
    25 }
    26 int main()
    27 {
    28     int a,b;
    29     while(1)
    30     {
    31     printf("For a^b input a and b:");
    32     scanf("%d%d",&a,&b);
    33     printf("The recursion method:
    ");
    34     printf("%d
    ",recursion(a,b));
    35     printf("The loop method:
    ");
    36     printf("%d
    ",loop(a,b));
    37     }
    38     return 0;
    39 }
    复制代码

    原理:

    对应于递归算法,以下是算法依据:

    直接乘要做998次乘法。但事实上可以这样做,先求出2^k次幂:

    3 ^ 2 = 3 * 3
    3 ^ 4 = (3 ^ 2) * (3 ^ 2)
    3 ^ 8 = (3 ^ 4) * (3 ^ 4)
    3 ^ 16 = (3 ^ 8) * (3 ^ 8)
    3 ^ 32 = (3 ^ 16) * (3 ^ 16)
    3 ^ 64 = (3 ^ 32) * (3 ^ 32)
    3 ^ 128 = (3 ^ 64) * (3 ^ 64)
    3 ^ 256 = (3 ^ 128) * (3 ^ 128)
    3 ^ 512 = (3 ^ 256) * (3 ^ 256)

    再相乘:

    以下是对应非递归算法:

    3 ^ 999
    = 3 ^ (512 + 256 + 128 + 64 + 32 + 4 + 2 + 1)
    = (3 ^ 512) * (3 ^ 256) * (3 ^ 128) * (3 ^ 64) * (3 ^ 32) * (3 ^ 4) * (3 ^ 2) * 3

  • 相关阅读:
    JavaScript 定时器
    JavaScript 面向对象
    JavaScript 数组Array
    JavaScript 基础
    HTML 基础
    HTML 常用标签
    python 线程/进程模块
    python GIL锁
    python 网络编程--socket模块/struct模块
    python 异常处理,约束
  • 原文地址:https://www.cnblogs.com/bendantuohai/p/4499350.html
Copyright © 2011-2022 走看看