P4884多少个1?-exBSGS

P4884

题目描述

题目描述

题解

构造,exBSGS
显然当前这种连续 N N N 1 1 1的形式并不好做,我们考虑构造成方幂的形式
其实非常好想到
1 0 N − 1 9 = 111...1 ( N \frac{10^N-1}{9}=111...1(N 910N1=111...1(N 1 ) 1) 1)
那么原式子就转换为了
⇒ 1 0 N ≡ 9 ∗ m + 1 ( m o d K ) \Rightarrow 10^N\equiv 9*m+1\pmod{K} 10N9m+1(modK)
那么由于 g c d ( 10 , K ) gcd(10,K) gcd(10,K)不一定为1,那么考虑用exBSGS求解即可

代码

#include<bits/stdc++.h>
#include <tr1/unordered_map>
#define int long long
using namespace std;
std::tr1::unordered_map<int,int>M;
int read(){
	int f=1,re=0;char ch;
	for(ch=getchar();!isdigit(ch)&&ch!='-';ch=getchar());
	if(ch=='-'){f=-1,ch=getchar();}
	for(;isdigit(ch);ch=getchar()) re=(re<<3)+(re<<1)+ch-'0';
	return re*f;
}
int gcd(int a,int b){return b?gcd(b,a%b):a;}
int ksm(int a,int b,int mod){
	int ans=1;
	while(b){
		if(b&1) ans=ans*a%mod;
		a=a*a%mod;
		b>>=1;
	}return ans;
}
int qmul(int a,int b,int mod){
	int ans=0;
	while(b){
		if(b&1) ans=(ans+a)%mod;
		a=(a+a)%mod;
		b>>=1;
	}return ans;
}
int bsgs(int a,int b,int p,int ad){
	M.clear();
	int m=sqrt(p)+1,s=1;
	for(int i=0;i<m;i++,s=qmul(s,a,p)) M[qmul(s,b,p)]=i;
	for(int i=0,tmp=s,s=ad;i<=m;i++,s=qmul(s,tmp,p))
		if(M.find(s)!=M.end())
			if(i*m-M[s]>=0) return i*m-M[s];
	return -1; 
}
int exbsgs(int a,int b,int p){
	a%=p,b%=p;
	if(b==1||p==1) return 0;
	int d,ad=1,cnt=0;
	while((d=gcd(a,p))^1){
		if(b%d) return -1;
		cnt++,b/=d,p/=d;
		ad=qmul(ad,a/d,p);
		if(ad==b) return cnt;
	}int ans=bsgs(a,b,p,ad);
	if(ans<0) return -1;
	else return ans+cnt;
}
signed main(){
	int b=read(),p=read();
	b=qmul(b,9,p)+1;
	printf("%lld\n",exbsgs(10,b,p));
 	return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值