给你一个整数d,求两个数字a和b使得a+b = d并且 ab = d.
可知a+b = ab 将b= d-a带入可得a^2 -ad + d = 0.不就是求一元二次方程的解吗?果断上牛顿迭代法,然而坑了我半个多小时。
牛顿迭代法即x -= f(x)/f’(x) ,但是如果用精度作为迭代的条件的时候会有一点小问题(输出nan,nan),所以我又加了一个变量cnt,控制迭代的次数。
#include <bits/stdc++.h>
using namespace std;
long double a,n;
int t,cnt;
int main(){
//freopen("data.in","r",stdin);
//freopen("data.out","w",stdout);
cin>>t;
while(t--){
cin>>n;
a = n/4;cnt = 1;
while(fabs(a*a-a*n+n)>1e-10&&cnt<500){
a = a - (a*a-a*n+n) / (2*a-n);
cnt++;
}
if(fabs(a*a-a*n+n)>1e-10) printf("N\n");
else cout<<'Y'<<' '<<setiosflags(ios::fixed)<<setprecision(10)<<a<<' '<<n-a<<endl;
}
return 0;
}