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

Hello guys, now we are going to print first k digits of 1/n where n is a positive integer using Python. If you are here, then you are moving in the right direction looking for the solution. Let me first explain the algorithm of this problem.

Initially input the number n from the user. Then input the number k that is the number of digits. Now you are going to learn how to write the code in such a way it prints the first k digits to the output after giving inputs. So in the code, We use Divide and multiply.we are dividing the 1 with n and we get floating number less than 1. Then we are Multiplying k with 10 and in turn, multiplying with that floating number and converting the whole result into integer and printing that integer gives us the first k digits of 1/n.

Whereas if n is equal to 1, this is not going to work because 1/1 is no more a floating number and here we are not going to convert y into integer because its already an integer, but we are converting into a string and reverse that string. print that string.

First k digits of 1/n in Python

n=int(input("Enter the integer: "))
y=1/n
k=int(input("Enter the number of digits: "))
h=pow(10,k)
y=int(y*h)
if n==1:
    y=str(y)
    print("The first "+str(k)+"digits are:"+str(y[::-1]))
else:
    print("The first "+str(k)+"digits are:"+str(y))

Input:

Enter the integer: 1 
Enter the number of digits: 5

Output:

The first 5 digits are: 00001

In the above code, one divides the n and multiply with 10 inturn multiply with the number of digits and convert it into the integer and prints the number.

If n is equal to 1, then y is converted to a string and does a sting operation [::-1]  which reverse the string. I hope you guys enjoyed it.

Also read: Find minimum number of jumps to reach end in Python

Leave a Reply

Your email address will not be published. Required fields are marked *