[BZOJ3817]Sum

[BZOJ3817]Sum

试题描述

给定正整数N,R。求

输入

第一行一个数 T,表示有 T 组测试数据。
接下来 T 行,每行两个正整数 n,r。

输出

输出 T 行,每行一个整数表示答案。

输入示例

3
3 5
3 6
3 7

输出示例

3
1
-1

数据规模及约定

对于 100% 的数据,满足 n≤10^9,r≤10^4,T≤10^4。

题解

新技能:类欧几里得算法。

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <algorithm>
#include <cmath>
using namespace std;

const int BufferSize = 1 << 16;
char buffer[BufferSize], *Head, *Tail;
inline char Getchar() {
	if(Head == Tail) {
		int l = fread(buffer, 1, BufferSize, stdin);
		Tail = (Head = buffer) + l;
	}
	return *Head++;
}
int read() {
	int x = 0, f = 1; char c = Getchar();
	while(!isdigit(c)){ if(c == '-') f = -1; c = Getchar(); }
	while(isdigit(c)){ x = x * 10 + c - '0'; c = Getchar(); }
	return x * f;
}

#define LL long long
int gcd(int a, int b) { return b ? gcd(b, a % b) : a; }
int r;
double x;
int f(int a, int b, int c, int n) {
	if(!n) return 0;
	int t = gcd(gcd(a, b), c); a /= t; b /= t; c /= t;
	int c1 = c - (LL)((b * x + c) / a) * a;
	LL s = (LL)((b * x + c) / a) * ((LL)n * (n + 1) >> 1) + n * (LL)((b * x + c1) / a * n);
	return s - f(b * b * r - c1 * c1, a * b, -a * c1, (b * x + c1) / a * n);
}

int main() {
	int T = read();
	while(T--) {
		int n = read(); r = read();
		x = sqrt(r);
		if(x == (int)x && (r & 1)) printf("%d\n", (n & 1) ? -1 : 0);
		else printf("%d\n", n + (f(2, 1, 0, n) << 2) - (f(1, 1, 0, n) << 1));
	}
	
	return 0;
}

记得特判 r 是完全平方奇数的情况。(我也不知道为啥。。。)并且记得在函数 f(a, b, c, n) 中要给 a, b, c 约分。

转载于:https://www.cnblogs.com/xiao-ju-ruo-xjr/p/7157945.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值