abs

鏈接:http://acm.hust.edu.cn/vjudge/problem/440426/origin

題目:Given a number x, ask positive integer  , 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.

題意:給出一個數,求距離他最近的一個滿足條件的數與他的差。條件是這個數的每個質因子出現兩次。

分析:其實是一個分解質因數的題目。首先可以把距離x最近的所有質因數出現兩次的問題優化爲:距離根號x最近的每個質因數只出現一次的問題。之後對根號x向下向上找到兩個滿足條件的數,比較差值就好了。

題解:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <string>
#include <cstring>
#include <functional>
#include <cmath>
#include <cctype>
#include <cfloat>
#include <climits>
#include <complex>
#include <deque>
#include <list>
#include <set>
#include <utility>
#define rt return
#define fr freopen("in.txt","r",stdin)
#define fw freopen("out.txt","w",stdout)
#define ll long long
#define ull unsigned long long
#define detie ios_base::sync_with_stdio(false);cin.tie(false);cout.tie(false)
#define pii pair<int,int>
#define lowbit(x) x&(-x)
using namespace std;
#define maxi 0x3f3f3f3f
#define MAX 100010

bool factor(ll n)
{
	set<int> s;
	ll t = (ll)sqrt(n);
	bool flag = true;
	for (int i = 2; i <= t&&flag; i++)
	{
		while (n%i==0&&flag)
		{
			n /= i;
			if (s.count(i))
			{
				flag = false;
				break;
			}
			s.insert(i);
		}
	}
	rt flag;
}

int main()
{
	//fr;
	detie;
	int T;
	cin >> T;
	while (T--)
	{
		ll n;
		cin >> n;
		ll tn1 = (ll)sqrt(n);
		ll tn2 = tn1+1;
		ll ans = 1e18;
		while (!factor(tn1)&&tn1>=2)
		{
			tn1--;
		}
		if (tn1!=1)//便捷處理需要小心謹慎。
			ans = min(ans, n - tn1*tn1); 
		while (!factor(tn2) && tn2 <=1000000000)
		{
			tn2++;
		}
		if(tn1!=1000000001)
			ans = min(ans, tn2*tn2 - n);
		cout << ans << endl;
	}
	rt 0;
}

發佈了59 篇原創文章 · 獲贊 0 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章