Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- /// Global variables that are used in multiple functions in the code
- #define NMAX 1000005
- int n, d;
- int frq[NMAX], mem[NMAX], adp[NMAX];
- /// Setting up the array "mem";
- void Set_Up()
- {
- for(int i = 0; i < NMAX; ++i) mem[i] = -1;
- }
- /*
- This function is meant to help us simulate how division is being done manually.
- It will be used both in the "Calculate_Before_Decimal_Point" and "Calculate_After_Decimal_Point".
- */
- int calc(int step)
- {
- int c = 0;
- while(n >= d)
- {
- n -= d;
- c++;
- }
- if(step == 1) frq[n]++;
- return c;
- }
- /*
- Calculating the digits before the decimal point is trivial, we just have to simulate how manual division works, which was already done with the function above.
- All that remains is to call the function.
- */
- void Calculate_Before_Decimal_Point()
- {
- printf("%d", calc(0));
- }
- /*
- By far, this is the most complex function of the entire code. First, it makes use of the function "calc" to simulate the manual division.
- The array adp is used to store the necessary information to give a proper output while the array "mem" is used to remember important information about calculations.
- */
- void Calculate_After_Decimal_Point()
- {
- int idx = 1;
- int has_repeating = 0;
- printf(".");
- while (n != 0)
- {
- if (mem[n] != -1) {
- has_repeating = 1;
- break;
- }
- // Mark the position of the remainder
- mem[n] = idx;
- n *= 10;
- adp[idx++] = n / d;
- n = n % d;
- if (idx >= 10000) {
- return;
- }
- }
- // Printing the digits after the decimal point
- for (int i = 1; i < idx; ++i)
- {
- // If a repeating sequence is found, mark it
- if (has_repeating && i == mem[n]) {
- printf("[");
- }
- printf("%d", adp[i]);
- }
- // If repeating, close the bracket
- if (has_repeating) {
- printf("]");
- }
- }
- int main()
- {
- /// Setting up one of the arrays for future use
- Set_Up();
- /// Reading the necessary input
- scanf("%d %d", &n, &d);
- /// Printing out the mathematical symbols
- printf("%d", n);
- printf("/");
- printf("%d", d);
- printf(" = ");
- /// Calculating the digits that are before the decimal point
- Calculate_Before_Decimal_Point();
- /// Calculating the digits that are after the decimal point (if there are any at all)
- if (n) Calculate_After_Decimal_Point();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement