题意:给出n,输出两个数a和b使得a+b=n且lcm(a,b)最小
思路一:开始暴力for循环打表找最小值看规律,猜了一发素数,水过了hh
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
typedef long long ll;
const int N=1e6+10;
int primes[N],cnt;
bool vis[N];
bool is_primes(int n)
{
if(n<2)return false;
for(int i=2;i<=n/i;i++){
if(n%i==0)return false;
}
return true;
}
void get(int n)
{
for(int i=2;i<=n;i++){
if(!vis[i])primes[cnt++]=i;
for(int j=0;i*primes[j]<=n;j++){
vis[i*primes[j]]=true;
if(i%primes[j]==0)break;
}
}
}
int main()
{
get(1e6);
ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
int t;
cin>>t;
while(t--){
ll n;
cin>>n;
if(is_primes(n))cout<<1<<' '<<n-1<<endl;
else{
for(int i=0;i<cnt;i++){
if(n%primes[i]==0){
cout<<n/primes[i]<<' '<<n-n/primes[i]<<endl;
break;
}
}
}
}
return 0;
}
ac后查了一下博客题解看到有比较好的分析,此处请参考这位博主的分析
假设a<=b,a+b=n,那么lcm(a,b)>=b,那么要使得lcm最小肯定要让他等于b,也就是说b%a=0且a+b=n,则b=ka,则a+ka=n–>(k+1)*a=n,那么n%a=0,这样的话只要枚举k判断n是否可以整除k+1即可,则a=n/(k+1),b=n-a,另,如果n是素数n是不会有因数的,因此,素数要另外判断
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
typedef long long ll;
bool is_primes(int n)
{
if(n<2)return false;
for(int i=2;i<=n/i;i++){
if(n%i==0)return false;
}
return true;
}
int main()
{
ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
int t;
cin>>t;
while(t--){
ll n;
cin>>n;
if(is_primes(n))cout<<1<<' '<<n-1<<endl;
else{
for(int i=2;i<=n/2;i++){
if(n%i==0){
cout<<n/i<<' '<<n-n/i<<endl;
break;
}
}
}
}
return 0;
}