easy
0 views
Nth Decimal Place
Find the digit at the Nth decimal place when dividing X by Y
Understand the Problem
Problem Statement
Nth Decimal Place: The program must accept three integers X, Y, and N as the input. The program must print the digit present in the Nth decimal place right to the decimal point when X is divided by Y as the output.
Note: If the number of digits in the decimal part of the result is less than N, then print 0 as the output.
Constraints
- 1 ≤ X, Y ≤ 10^6
- 1 ≤ N ≤ 10^6
- Division result should be calculated with sufficient precision to determine the Nth decimal place
Examples
Example 1
Input
22 7 12Output
7Explanation
22/7 = 3.142857142857... The 12th decimal digit is 7.
Example 2
Input
4 2 1Output
0Explanation
4/2 = 2.0, so there are no decimal places. The 1st decimal digit is 0.
Example 3
Input
1 3 5Output
3Explanation
1/3 = 0.333333... The 5th decimal digit is 3.
Solution
#include <stdio.h>
int main() {
int x, y, n;
scanf("%d %d %d", &x, &y, &n);
// Get the remainder after integer division
int remainder = x % y;
// If no decimal part exists
if (remainder == 0) {
printf("0\n");
return 0;
}
// Find the Nth decimal digit
for (int i = 0; i < n; i++) {
remainder *= 10;
int digit = remainder / y;
remainder = remainder % y;
// If we've reached the end of decimal expansion
if (remainder == 0) {
if (i == n - 1) {
printf("%d\n", digit);
} else {
printf("0\n");
}
return 0;
}
// If this is the Nth decimal place
if (i == n - 1) {
printf("%d\n", digit);
return 0;
}
}
return 0;
}Time:O(N) - We perform N iterations to reach the Nth decimal place
Space:O(1) - Only using a constant amount of extra space
Approach:
The C solution uses modular arithmetic to find the Nth decimal digit:
- Read input values X, Y, and N
- Calculate the remainder after integer division (X % Y)
- If remainder is 0, there's no decimal part, so output 0
- Loop N times to reach the Nth decimal place:
- Multiply remainder by 10
- The quotient when dividing by Y gives the current decimal digit
- Update remainder to (remainder * 10) % Y
- If remainder becomes 0 during the process, we've reached the end of decimal expansion
- Output the digit found at the Nth position
This approach avoids floating-point precision issues and works efficiently.
Visual Explanation
Loading diagram...