Problemconsider a function which, for a given whole number N, returns the number of ones required when writing out all numbers between 0 and N. for example, F (13) = 6. notice that F (1) = 1. what is the next largest N such that F (n) = n? Algorithm idea: calculate the number of 1 in each number cyclically. If F (n) = N is satisfied, exit. Otherwise, continue. The Code is as follows:
/**//*********************************** *************************************
* 0 ~ The number of 1 values between N, for example, F (13) = 6.
* The number of 13.1, is 6.
* Requirement: enter a positive integer n to obtain F (N) and solve F (n) = n.
**************************************** ********************************/
# Include <stdio. h>
# Include <string. h>
# Include <windows. h>
Class calculationtimes
...{
Public:
Calculationtimes ()...{}
~ Calculationtimes ()...{}
Int gettimes (int n );
};
// Calculate the number of 1 in positive integer n
Int calculationtimes: gettimes (int n)
...{
Int COUNT = 0;
While (N)
...{
If (N % 10 = 1)
Count ++;
N/= 10;
}
Return count;
}
// Display menu
Void show_menu ()
...{
Printf ("---------------------------------------------");
Printf ("input command to test the program ");
Printf ("I or I: Input n to test ");
Printf ("G or G: Get n to enable F (n) = N ");
Printf ("Q or Q: Quit ");
Printf ("---------------------------------------------");
Printf ("$ input command> ");
}
Void main ()
...{
Char sinput [10];
Int N;
Show_menu ();
Scanf ("% s", sinput );
While (stricmp (sinput, "Q ")! = 0)
...{
Int T = 0, Count = 0;
If (stricmp (sinput, "I") = 0)
...{
Printf ("Please input an integer :");
Scanf ("% d", & N );
Count = 0;
Calculationtimes OBJ;
T = gettickcount ();
For (INT I = 1; I <= N; I ++)
Count + = obj. gettimes (I );
T = gettickcount ()-T;
Printf ("Count = % d time = % d", Count, t );
}
Else if (stricmp (sinput, "G") = 0)
...{
Calculationtimes OBJ;
N = 2;
Count = 1;
T = gettickcount ();
While (1)
...{
Count + = obj. gettimes (N );
If (COUNT = N)
Break;
N ++;
}
T = gettickcount ()-T;
Printf ("F (n) = n = % d time = % d", N, t );
}
// Enter the command
Printf ("$ input command> ");
Scanf ("% s", sinput );
}
}
The running result is as follows: