HDU4704 Sum (modulus of large numbers, deep understanding of Fermat's little theorem)

Sum




Simple Input

2

3

Simple Output

2

4

Idea: The original question killed people, and the original exchange position is a new one. The plug-in method C(1,n)+C(2,n)+...+C(n,n) = 2 ^n.

That is, to find 2^(n-1), but n is very large. Here, the modulus operation of large numbers and Fermat's little theorem are used.

If a and p are relatively prime, then a^(p-1)%p == 1 is always established, so this question can use this property.

Because 2^n %p== 2^(p-1)*2(n-(p-1))%p == 2^(p-1)%p*2(n-(p-1)) %p == 1*2(n-(p-1))%p.

So for this problem, we only need to calculate n%(p-1). How can n be so large modulo p-1?

1234%m == (((1*10+2)*10+3)*10+4 )%m == (((1%m*10+2)%m*10+3)%m*10+4)%m

It's solved!

Code:

#include<bits/stdc++.h>
#define mem(a,b) memset(a,b,sizeof(a))
#define mod 1000000007
using namespace std;
typedef long long ll;
const int maxn = 1e6+5;
const double esp = 1e-7;
const int ff = 0x3f3f3f3f;
map<int,int>::iterator it;

char s[maxn];

ll big_mod()
{
	ll ans = s[0] - '0';
	int len ​​= strlen(s);
	
	for(int i = 1;i< len;i++)
		years = (years*10+s[i]-'0')%(mod-1);
	
	return ans;
}

ll quick_pow(ll x,ll y)
{
	ll ans = 1;
	while(y)
	{
		if(y&1)
			years = (years*x)%mod;
		y>>= 1;
		x = (x*x)%mod;
	}
	
	return ans;
}

intmain()
{
	while(~scanf(" %s",s))
	{
		ll m = big_mod();
		cout<<quick_pow(2,m-1)<<endl;
	}
	
	return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325973131&siteId=291194637