Find the Nth digit in the proper fraction of two numbers
Last Updated :
16 Dec, 2022
Given three integers P, Q and N where P < Q, the task is to compute the fraction value of P / Q and find the Nth digit after the decimal.
Example
Input: P = 1, Q = 2, N = 1
Output: 5
(1 / 2) = 0.5 and 5 is the first digit after the decimal.
Input: P = 5, Q = 6, N = 5
Output: 3
(5 / 6) = 0.833333333…
Approach: Initialize an integer variable res that stores the resultant Nth digit. Now, while N > 0 do the following:
- Decrement N by 1.
- To compute the digit, update the value P = P * 10.
- Compute res = P / Q and update P = P % Q.
Finally, print the res.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int findNthDigit( int p, int q, int N)
{
int res;
while (N > 0) {
N--;
p *= 10;
res = p / q;
p %= q;
}
return res;
}
int main()
{
int p = 1, q = 2, N = 1;
cout << findNthDigit(p, q, N);
return 0;
}
|
Java
import java.io.*;
public class GFG
{
static int findNthDigit( int p,
int q, int N)
{
int res = 0 ;
while (N > 0 )
{
N--;
p *= 10 ;
res = p / q;
p %= q;
}
return res;
}
public static void main(String args[])
{
int p = 1 , q = 2 , N = 1 ;
System.out.println(findNthDigit(p, q, N));
}
}
|
Python3
def findNthDigit(p, q, N) :
while (N > 0 ) :
N - = 1 ;
p * = 10 ;
res = p / / q;
p % = q;
return res;
if __name__ = = "__main__" :
p = 1 ; q = 2 ; N = 1 ;
print (findNthDigit(p, q, N));
|
C#
using System;
class GFG
{
static int findNthDigit( int p, int q, int N)
{
int res = 0;
while (N > 0)
{
N--;
p *= 10;
res = p / q;
p %= q;
}
return res;
}
public static void Main()
{
int p = 1, q = 2, N = 1;
Console.WriteLine(findNthDigit(p, q, N));
}
}
|
Javascript
<script>
function findNthDigit(p, q, N)
{
var res;
while (N > 0)
{
N--;
p *= 10;
res = parseInt(p / q);
p %= q;
}
return res;
}
var p = 1,
q = 2,
N = 1;
document.write(findNthDigit(p, q, N));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...