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



Input number N such that 1/N will return the output generated as decimal specified till the limit.

It is easy with Floating Point numbers but the challenge is without using them.

Input − n=5 k=5
Output − 20000
It means if n=5 and k=5 than after dividing 1/5 the output should be displayed till 5 decimal points.

Algorithm

Start Step 1 -> Declare int variable n to 9 and k to 7 and remain to 1 and i Step 2-> Loop for i to 0 and i<k and i++    Print ((10*remain)/n)    Remain = (10*remain)%n Step 3-> end Loop For Stop

Example

#include<stdio.h> int main() {    int n = 9, k = 7, remain=1,i ; // taking n for 1/n and k for decimal values    printf("first %d digits of %d are : ",k,n);    for(i=0;i<k;i++) {       printf("%d",((10 * remain) / n));       remain = (10*remain) % n;    }    return 0; }

Output

If we run above program then it will generate following output.

first 7 digits of 9 are : 1111111
Updated on: 2019-08-08T08:59:15+05:30

203 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements