Print first k digits of 1/n where n is a positive integer in C Program

In C programming, we need to find the first k digits of the decimal representation of 1/n without using floating-point arithmetic. This involves simulating the long division process using integer operations only.

Syntax

// Basic approach using modular arithmetic
for(i = 0; i < k; i++) {
    digit = (10 * remainder) / n;
    remainder = (10 * remainder) % n;
}

Algorithm

The algorithm simulates manual long division −

Step 1: Initialize remainder = 1 (representing the dividend "1")
Step 2: For each decimal position (k times):
   a) Multiply remainder by 10
   b) Divide by n to get the current digit
   c) Update remainder using modulo operation
Step 3: Print each calculated digit

Example 1: Basic Implementation

Here's how to print the first k digits of 1/n −

#include <stdio.h>

int main() {
    int n = 9, k = 7, remainder = 1, i;
    
    printf("First %d digits of 1/%d are: ", k, n);
    
    for(i = 0; i < k; i++) {
        int digit = (10 * remainder) / n;
        printf("%d", digit);
        remainder = (10 * remainder) % n;
    }
    
    printf("<br>");
    return 0;
}
First 7 digits of 1/9 are: 1111111

Example 2: Different Input Values

Let's test with different values of n and k −

#include <stdio.h>

int main() {
    int n = 5, k = 5, remainder = 1, i;
    
    printf("First %d digits of 1/%d are: ", k, n);
    
    for(i = 0; i < k; i++) {
        int digit = (10 * remainder) / n;
        printf("%d", digit);
        remainder = (10 * remainder) % n;
    }
    
    printf("<br>");
    return 0;
}
First 5 digits of 1/5 are: 20000

How It Works

The algorithm mimics long division by hand −

  • Step 1: Start with remainder = 1 (the numerator)
  • Step 2: Multiply by 10 and divide by n to get the next decimal digit
  • Step 3: The new remainder is (10 * remainder) % n
  • Step 4: Repeat for k iterations

Key Points

  • This method avoids floating-point precision issues
  • Works for any positive integer n
  • Time complexity: O(k) where k is the number of digits required
  • Space complexity: O(1)

Conclusion

This integer-only approach effectively calculates decimal digits of 1/n by simulating long division. It provides precise results without floating-point arithmetic limitations and works efficiently for any positive divisor.

Updated on: 2026-03-15T11:23:38+05:30

273 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements