"Problem description"
M, N is known as an integer, and the following two conditions are met:
①m, n∈{1,2,...,k}, or 1≤m,n≤k, (1≤k≤109).
② (n2-m*n-m2) 2=1
Your task is to programmatically enter a positive integer k, to find a set of M, n that satisfies the above two conditions, and to make the value of M2+N2 the largest. For example, if you enter k=1995 from the keyboard, the output: m=987 n=1597.
"Input Sample"
1995
"Output Example"
m=987
n=1597
The code is as follows:
1 Longm,n,k;2 Doubledelt1,delt2,n1,n2;3scanf"%d",&k);4 for(m=k;m>=1; m--)5 {6DELT1=SQRT (5*m*m+4);7n1= (M+DELT1)/2;8n=N1;9 if(n==n1&&n<=k) Break;Ten OneDELT2=SQRT (5*m*m-4); AN2= (M+DELT2)/2; -n=N2; - if(n==n2&&n<=k) Break; the } -printf"m=%d\nn=%d\n", m,n);View Code
Annotations: The algorithm is very good, concise, high efficiency, but there is a problem is obvious, that is, when the value of K reaches 10^9, for the Loop, M from K to 1 times the calendar. When the value of M is 10^9, the m^2 will overflow when the delt is calculated. And it is not only when K reaches 10^9 that the problem arises when K reaches 10^5. It seems not so easy to write a function to achieve the square root of a high-precision number. So, you can look at the following recursive method.
The standard answer is:
The code is as follows:
1 intn=1, m=1, k,t;2Cin>>K;3 Do4 {5t=n+m;6 if(t<=k)7 {8m=N;9n=T;Ten } One } A while(t<=k); -cout<<"m="<<m<<endl<<"n="<<n;View Code
annotations: at first reading the algorithm, it is impossible to understand why it is the same law as the Fibonacci sequence. Later check the information, reading comprehension, finally read understand. Make a note below.
Extremum problem (ACMS)