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

 Segment
Time Limit:1000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u



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 2q1018,1P1018,1T10.
 

 

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<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
const int INF = 0x3f3f3f3f;
typedef long long LL;
LL js(LL x, LL y, LL MOD){
    LL ans = 0;
    while(x){
        if(x&1){
            ans += y;
            ans %= MOD;
        }
        x >>= 1;
        y <<= 1;
        y %= MOD;
    }
    return ans;
}
int main(){
    LL P, q;
    int T;
    scanf("%d", &T);
    while(T--){
        scanf("%lld%lld", &q, &P);
        if((q - 1) & 1){
            printf("%lld\n", js(q - 1, (q - 2) / 2, P));
        }
        else if((q - 2) & 1){
            printf("%lld\n", js(q - 2, (q - 1) / 2, P));
        }
    }
    return 0;
}

 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-- > 0){
            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);
        }
    }
}

 

posted @ 2016-04-20 19:17  handsomecui  阅读(1229)  评论(0编辑  收藏  举报