码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-04-20 20:14:15      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:

 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
 

 题解:给一个线段,让求线段与坐标轴之间空白部分的整数点的个数,很容易找到规律;

x + y < q - 1;

(q - 1)*(q - 1) - (1 + 2 + *** + q - 1);

(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;
}

 

 

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

标签:

原文地址:http://www.cnblogs.com/handsomecui/p/5413986.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!