题目链接:hdoj 5666 Segment
Segment
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1044 Accepted Submission(s): 382
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
题意:给定x + y = p的线段,连接原点到该线段上所有的整数点得到若干条直线,问你在该三角形里面的整数点有多少个不在任意一条直线上。
公式q++, (q-2) * (q-3) / 2。
首选java:
import java.util.*;
import java.math.*;
import java.util.regex.*;
public class Main {
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
int t = cin.nextInt();
BigInteger x = BigInteger.valueOf(-2);
BigInteger y = BigInteger.valueOf(-3);
BigInteger z = BigInteger.valueOf(1);
while(t --> 0) {
BigInteger q = cin.nextBigInteger();
q = q.add(z);
BigInteger p = cin.nextBigInteger();
BigInteger ans = q.add(x);
BigInteger res = q.add(y);
ans = ans.multiply(res);
//System.out.println(ans);
ans = ans.divide(x.negate());
System.out.println(ans.mod(p));
}
}
}
二进制优化乘法:
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
#include <iostream>
#include <cmath>
#include <queue>
#include <stack>
#define ll o<<1
#define rr o<<1|1
#define CLR(a, b) memset(a, (b), sizeof(a))
using namespace std;
typedef long long LL;
typedef pair<int, int> pii;
const int INF = 0x3f3f3f3f;
const int MAXN = 1e3 + 10;
LL multi(LL a, LL b, LL p)
{
LL exp = a % p, res = 0;
while(b) {
if (b & 1) { //b的最低位是否为1
res = res + exp;
if (res >= p) res = res - p;
}
exp = exp *2;
if (exp > p) exp = exp - p;
b >>= 1; //将b除以2
}
return res;
}
int main()
{
LL p, q;
int t; scanf("%d", &t);
while(t--) {
scanf("%lld%lld", &q, &p);
q++; LL qq;
if(q % 2 == 0) {
qq = q - 3;
q -= 2; q >>= 1;
}
else {
qq = q - 2;
q -= 3; q >>= 1;
}
//cout << q << ' ' << qq << endl;
printf("%lld\n", multi(q, qq, p));
}
return 0;
}