K - Can you find it
Time Limit:5000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64u
Description
Given a prime number
C(1≤C≤2×105)
, and three integers k1, b1, k2
(1≤k1,k2,b1≤109)
. Please find all pairs (a, b) which satisfied the equation
ak1⋅n+b1
+
bk2⋅n−k2+1
= 0 (mod C)(n = 1, 2, 3, …).
Input
There are multiple test cases (no more than 30). For each test, a single line contains four integers C, k1, b1, k2.
Output
First, please output “Case #k: “, k is the number of test case. See sample output for more detail.
Please output all pairs (a, b) in lexicographical order.
(1≤a,b<C)
. If there is not a pair (a, b), please output -1.
Sample Input
23 1 1 2
Sample Output
Case #1:
1 22
分析:
这是摘自http://blog.csdn.net/queuelovestack/article/details/48754331
写数学题要多动笔。
这题其实就是对快速幂取余的考核。下面我的代码里面有两种方法。一种是以前我写的二分的方法,一种是利用二进制的方法。(二进制可以再很多方面将我们的程序优化,也有很多的应用很有必要去认真学学!!!)
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
/*
//二分递归求快速幂取模
long long pow_mod(long long a,long long b,long long m)
{
long long t;
if(b==0) return 1;
if(b==1) return a%m;
t = pow_mod(a,b/2,m);
t = t*t%m;
if(b & 1)
t = t*a%m;
return t;
}
*/
//利用位运算求快速幂取模
long long pow_mod_(int a,int b,int m)
{
long long res=1,t=a%m;
while(b)//当b不为0时
{
if(b&1)//当2进制最后一位位1时
res = (res*t)%m;
t=(t*t)%m;//计算下一个2进制代表的值
b>>=1;
}
return res%m;
}
int main()
{
int C,k1,b1,k2;
long long a,b,s;
int k=1;
bool flag;
while(scanf("%d%d%d%d",&C,&k1,&b1,&k2)!=EOF)
{
flag = false;
printf("Case #%d:\n",k++);
for(int i=1;i<C;i++)
{
a = pow_mod_(i,k1,C);
b = C-pow_mod_(i,k1+b1,C);
s = pow_mod_(b,k2,C);
if(a==s)
{
flag = true;
printf("%d %I64d\n",i,b);
}
}
if(!flag)
printf("-1\n");
}
return 0;
}