HDU-5778 abs

来源:互联网 发布:知乎怎么注册 编辑:程序博客网 时间:2024/05/16 15:05

原题链接

abs

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 1260    Accepted Submission(s): 439


Problem Description
Given a number x, ask positive integer y2, that satisfy the following conditions:
1. The absolute value of y - x is minimal
2. To prime factors decomposition of Y, every element factor appears two times exactly.
 

Input
The first line of input is an integer T ( 1T50)
For each test case,the single line contains, an integer x ( 1x1018)
 

Output
For each testcase print the absolute value of y - x
 

Sample Input
511124290871699579095
 

Sample Output
23656724470


设p1 = sqrt(x), p2 = p1 +1, P1向小方向枚举,p2向大方向枚举,找到一个p使p的每种质因子仅有一个且abs(p*p-x)达到最小.

#include <iostream>#include <algorithm>#include <cstring>#include <cstdio>#include <vector>#include <map>#include <cmath>#define maxn 100005#define INF 1000000000using namespace std;typedef long long ll;int num[maxn], cnt;ll v[maxn];void prime(){for(ll i = 2; i < maxn; i++){if(num[i] == 0){v[cnt++] = i;}for(ll j = i * i; j < maxn; j += i) num[j] = 1;}}bool judge(ll p){if(p < 2)  return false;for(int i = 0; i < cnt&& v[i] * v[i] <= p; i++){ll d = v[i] * v[i];if(p % d == 0) return false;}return true;}void solve(ll x){ll p1 = sqrt(x);ll p2 = p1 + 1;while(1){if(p1 >= 2 && x - p1 * p1 < p2 * p2 - x){if(judge(p1)){printf("%I64d\n", x - p1 * p1);    return ;}    p1--;}else{if(judge(p2)){printf("%I64d\n", p2 * p2 - x);        return ;}p2++;}}}int main(){//freopen("in.txt", "r", stdin);int t;prime();scanf("%d", &t);while(t--){ll x;scanf("%I64d", &x);solve(x);} return 0;}



0 0