原题为:CodeForces 1372B - Omkar and Last Class of Math。
B. Omkar and Last Class of Math
time limit per test 1 second
memory limit per test 256 megabytes
input standard input
output standard output
In Omkar’s last class of math, he learned about the least common multiple, or LCM. LCM(a,b) is the smallest positive integer x which is divisible by both a and b.
Omkar, having a laudably curious mind, immediately thought of a problem involving the LCM operation: given an integer n, find positive integers a and b such that a+b=n and LCM(a,b) is the minimum value possible.
Can you help Omkar solve his ludicrously challenging math problem?
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1≤t≤10). Description of the test cases follows.
Each test case consists of a single integer n (2≤n≤109).
Output
For each test case, output two positive integers a and b, such that a+b=n and LCM(a,b) is the minimum possible.
Example input
3
4
6
9
output
2 2
3 3
3 6
Note
For the first test case, the numbers we can choose are 1,3 or 2,2. LCM(1,3)=3 and LCM(2,2)=2, so we output 2 2.
For the second test case, the numbers we can choose are 1,5, 2,4, or 3,3. LCM(1,5)=5, LCM(2,4)=4, and LCM(3,3)=3, so we output 3 3.
For the third test case, LCM(3,6)=6. It can be shown that there are no other pairs of numbers which sum to 9 that have a lower LCM.
题目大意:
输入一个t表示有t组数据,对于每组数据输入一个n,求a+b==n且 lcm(a,b)尽可能的小。
题解:该题要求我们在满足a+b=n的情况下lcm(a,b)要尽可能的小。一开始我想的是直接用朴素的暴力算法与(a+b)/(最大公约数)进行求解,但不幸TLE了。所以我转为运用对n的范围进行开方进行减小循环范围(不朴素的暴力算法),然后利用求素数的思想,开始从2进行寻找可以对n取模为0的值,如果有该数则证明有可以n分成两个数,从而lcm达到最小值,然后输出n/i与n-n/i(a+b=n),如果遍历完无该值则只能输出1和n-1。
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n,temp=1;
scanf("%d",&n);
int m=sqrt(n)+1;
int lin1,lin2;
for(int i=2;i<=m;i++)
{
lin1=n/i;
lin2=n-lin1;
if(n%i==0)
{
printf("%d %d\n",lin1,lin2);
temp=0;
break;
}
}
if(temp)
{
lin1=1;
lin2=n-1;
printf("%d %d\n",lin1,lin2);
}
}
return 0;
}