SHUOJ easy problem

描述

As we know, gcd(A, B) means the Greatest Common Divisor (GCD) of A and B.

But zy thinks it is so easy to just let you calculate it.
So now your task is to calculate gcd(A, B^B),it is easy right?

Notice: B ^ B means B multiply by himself B times

输入输出

input
Multiply test case, each case per line.
Each line 2 integers A, B, 1 <= A, B <= 1000


output
For each test case output one line( one number ), indicating the value of gcd (A, B^B)

想法

这道题主要是B^B数量太大,提示我们利用 辗转相除法 来计算最大公约数。
当然本着简单暴力的原则我先将B^B不断取余算出B^B%A的值,再来求gcd,虽然AC了但还是希望能改进它。

代码

#include <iostream>
using namespace std;

int gcd(int a, int b)//求最大公约数
{
    if(b==0)
        return a;
    else
        return gcd(b, a%b);
}

int main()
{
    int a,b,i;
    while(cin>>a>>b)
    {
        int cnt=1;
        for(i=1;i<=b;i++)//计算B**B模A的余数
            cnt = (cnt*b) % a;
        int answer = gcd(a,cnt);
        cout<<answer<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/waveviewer/article/details/81193695