|
1 | 1 | package com.thealgorithms.others;
|
2 | 2 |
|
3 |
| -import java.util.Scanner; |
4 |
| - |
5 | 3 | public final class RootPrecision {
|
6 | 4 | private RootPrecision() {
|
7 | 5 | }
|
8 | 6 |
|
9 |
| - public static void main(String[] args) { |
10 |
| - // take input |
11 |
| - Scanner scn = new Scanner(System.in); |
12 |
| - |
13 |
| - // n is the input number |
14 |
| - int n = scn.nextInt(); |
15 |
| - |
16 |
| - // p is precision value for eg - p is 3 in 2.564 and 5 in 3.80870. |
17 |
| - int p = scn.nextInt(); |
18 |
| - System.out.println(squareRoot(n, p)); |
19 |
| - |
20 |
| - scn.close(); |
21 |
| - } |
22 |
| - |
23 |
| - public static double squareRoot(int n, int p) { |
24 |
| - // rv means return value |
25 |
| - double rv; |
26 |
| - |
27 |
| - double root = Math.pow(n, 0.5); |
28 |
| - |
29 |
| - // calculate precision to power of 10 and then multiply it with root value. |
30 |
| - int precision = (int) Math.pow(10, p); |
31 |
| - root = root * precision; |
32 |
| - /*typecast it into integer then divide by precision and again typecast into double |
33 |
| - so as to have decimal points upto p precision */ |
34 |
| - |
35 |
| - rv = (int) root; |
36 |
| - return rv / precision; |
| 7 | + /** |
| 8 | + * Calculates the square root of a number with the specified precision. |
| 9 | + * |
| 10 | + * @param number The number to calculate the square root of. |
| 11 | + * @param precision The number of decimal places of precision. |
| 12 | + * @return The square root of the number with the specified precision. |
| 13 | + */ |
| 14 | + public static double calculateSquareRoot(int number, int precision) { |
| 15 | + double rawRoot = Math.sqrt(number); // Calculate the square root using Math.sqrt |
| 16 | + double scalingFactor = Math.pow(10, precision); // Calculate the scaling factor for precision |
| 17 | + |
| 18 | + // Scale the square root, truncate the extra decimals, and rescale back |
| 19 | + return Math.round(rawRoot * scalingFactor) / scalingFactor; |
37 | 20 | }
|
38 | 21 | }
|
0 commit comments