Fast Power algorithm

Source: Internet
Author: User

Fast Power Algorithm idea: iterative/binary

We know a formula: a*b%c= (a%c*b%c)%c

If ab%c is required:

First, iteration

When B is odd: ab%c= ((A2) b/2*a)%c, Kee K=a2%c, that is (kb/2%c*a)%c

When B is even: ab%c= (A2) b/2%c, remember K=a2%c, that is to beg kb/2%c

Then the problem turns to Kb/2%c,

We assume that

Make the k1=a2%c, the problem turns to seek k1b/2%c

Make the k2=k12%c=a4%c, the problem turns to seek k2b/4%c

Make the k3=k22%c=a8%c, the problem turns to seek k3b/8%c

......

This process can be iterated, a start k=a, each b=b/2,k=k*k%c, whenever B is odd, the time of the K (also not squared) in the answer, to the last, b=1 (finally B must first = 1, then =0), the answer will be in, and then b=0 on the end of the algorithm.

#include <stdio.h>int main () {    int a,b,c,k,ans;    scanf ("%d%d%d", &a,&b,&c);    Ans=1;    K=a;    while (b) {        if (b%2)//b is an odd            ans=ans*k%c;        k=k*k%c;        B=B/2;    }    printf ("%d", ans);    return 0;}
Ii. binary

Suppose b= (18) 10 = (10010) 2

That Ab%c=a (2*a) (10000) 2%c=a2*a16%c

Each cycle is equivalent to the bits from right to left of B, and if it's 1, multiply K,

What is K? is a value of this bits of B, for example, to the second position from right to left of 10010, K=a (Ten) 2=a2, when the fifth position, K=a (10000) 2=a16

So each k=k*k%c,k change is: k=a (1) 2%c,k=a (+) 2%c,k=a (2), ...

#include <stdio.h>int main () {    int a,b,c,k,ans;    scanf ("%d%d%d", &a,&b,&c);    Ans=1;    K=a;    while (b) {        if (b&1)//b The last digit of the binary is 1            ans=ans*k%c;        k=k*k%c;        b=b>>1;//b binary minus the last    }    printf ("%d", ans);    return 0;}

  

Fast Power algorithm

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.