It can be said that mathematics is the cornerstone of the algorithm, then here, through the introduction of several mathematical topics to spy on how the mathematical thinking and programming organically together.
Cantor tables: There are the following numbers, the first item is 1/1, the second item is 1/2 the third item is 2/1, the fourth item is 3/1, fifth item 2/2,....。 Enter N to output the nth item.
1/1 1/2 1/3) 1/4 1/5
2/1 2/2 2/3 2/4
3/1 3/2 3/3
4/1 4/2
5/1
Sample input:
3
14
7
12345
Sample output:
2/1
2/4
1/4
59/99
Analysis: This is a typical search number law and then code to achieve the problem, he examines certain mathematical induction ability.
It is not difficult to see the "s" route along the diagonal, but for each slash, we can see the consistency of the analysis denominator.
For the input n, we first calculate how many full slashes are in front of it, recorded as K:
Then judging the k+1 of the ordinal of the diagonal of the nth item, this determines the increment direction of the numerator denominator.
If the k+1 is an even number, the denominator increments from the lower left to the upper right, and the numerator denominator is k+2.
The simple reference code is as follows.
#include <cstdio>#include<cmath>using namespacestd;intMain () {intN, K; while(SCANF ("%d", &n)! =EOF) {k= (int) Floor ((sqrt (8.0*n+1)-1)/2-1e-9);//Floor down rounding function inttemp = ((1+ k) *k)/2; printf ("k =%d temp =%d\n", K, temp); if(k +1) %2==0) printf ("%d/%d\n", N-temp,k +2-N +temp); Elseprintf ("%d/%d\n", K +2-N + temp,n-temp); }}
"Getting Started classic"--6.15