Exponential modulus algorithm

Source: Internet
Author: User
Tags modulus

Topic:

Given a A, b

Find out: A^a^a....^a (b a)

Input:

A, b

Output

Result of Operation

Examples:

2 3

Output: 16

Range: a,b<=10^9

We can get the answer first: ans=a^ (a^ (b-1))

However (a^ (b-1)) as the exponent is too big, must take the model

Make y= (a^ (b-1)), p=1e9+7

Y=k*φ (P) + (y%φ (p))

Because x^φ (p)ξ1 (mod p)

So a^φ (p)%p=1

So a^y=a^ (y%φ (p))

Because p is a prime number, φ (p) =p-1

So the a^ (b-1) mode p-1

You can do it with a quick power.

1#include <cstdio>2#include <iostream>3#include <algorithm>4#include <cstring>5 using namespacestd;6 intMod=1000000007;7 Long Longa,b,ans,s;8 Long LongQpow (Long LongXintYintmo)9 {Ten   Long Longres=1; One    while(y) A     { -       if(y&1) res= (res*x)%mo; -x= (x*x)%mo; they>>=1; -     } -   returnRes; - } + intMain () - { +Cin>>a>>b; AS=qpow (a,b-1, mod-1); atans=Qpow (a,s,mod); -cout<<ans; -}

Exponential modulus 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.