Problem Description
Silen August does not like to talk with others.She like to find some interesting problems.
Today she finds an interesting problem.She finds a segment x+y=q.The segment intersect the axis and produce a delta.She links some line between (0,0)and the node on the segment whose coordinate are integers.
Please calculate how many nodes are in the delta and not on the segments,output answer mod P.
Input
First line has a number,T,means testcase number.
Then,each line has two integers q,P.
q is a prime number,and 2≤q≤1018,1≤P≤1018,1≤T≤10.
Output
Output 1 number to each testcase,answer mod P.
Sample Input
1
2 107
Sample Output
0
题解:给一个线段,让求线段与坐标轴之间空白部分的整数点的个数,很容易找到规律;
(q - 1)(q - 2) / 2;
由于q是1e18,P也是1e18,相乘会超ll,所以想到用巧妙的方法把相乘换成相加;思路:把一个数化为二进制,例如3 * 5 = 1(二进制) * 5 + 10(二进制) * 5;具体看代码:
代码:
#include
#include
#include
#include
using namespace std;
const int INF = 0x3f3f3f3f;
typedef long long LL;
LL js(LL x, LL y, LL MOD){
LL ans = ;
while(x){
if(x&){
ans += y;
ans %= MOD;
}
x >>= ;
y <<= ;
y %= MOD;
}
return ans;
}
int main(){
LL P, q;
int T;
scanf("%d", &T);
while(T--){
scanf("%lld%lld", &q, &P);
if((q - ) & ){
printf("%lld\n", js(q - , (q - ) / , P));
}
else if((q - ) & ){
printf("%lld\n", js(q - , (q - ) / , P));
}
}
return ;
}
java:由于没有相等,packpage没有删除,错了半天。。。。。
//package 随笔;
import java.math.BigInteger;
import java.util.*;
//(q - 1)(q - 2) / 2;
public class Main {
public static void main(String[] s){
int T;
Scanner input = new Scanner(System.in);
T = input.nextInt();
BigInteger x = new BigInteger("-1");
BigInteger y = new BigInteger("-2");
while(T-- > ){
BigInteger q = input.nextBigInteger(), p = input.nextBigInteger();
BigInteger q1, q2;
//q = q.add(BigInteger.valueOf(1));
q1 = q.add(x);
q2 = q.add(y);
//System.out.println(q1 + "**" + q2);
q1 = q1.multiply(q2);
q1 = q1.divide(y.negate());
q1 = q1.mod(p);
System.out.println(q1);
}
}
}
本文介绍了一种解决计算特定线段与坐标轴所形成三角形内整数点数量问题的有效算法。考虑到输入数据范围较大,文章提出了一种避免溢出的乘法转换技巧,并通过二进制拆分的方法实现高效计算,最终输出结果模P。
&spm=1001.2101.3001.5002&articleId=114254711&d=1&t=3&u=a75ec2d3f7834fbbbff7ccc017a88384)
1098

被折叠的 条评论
为什么被折叠?



