java的segment_Segment(技巧 相乘转换成相加 + java)

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);

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值