Sunday, March 11, 2018

Square root

Square Root (Decimal)
Send Feedback

Given a number n, find the square root with an accuracy of d decimal points. n & d is provided by the user.

If the number is perfect square, print integer only. For eg. if n = 16 & d = 2, output should be 4
Input format : n and d
Sample Input 1 :
10 4
Sample Output 1 :
3.1622
Sample Input 2 :
16 2
Sample Output 2 :
4
Sample Input 3 :
10 0
Sample Output 3 :
3


import java.util.Scanner;
public class Main {

public static void main(String[] args) {
// Write your code here
Scanner s=new Scanner(System.in);
int  n=s.nextInt();
int d=s.nextInt();
float sqrt = 0;
int temp = (int) Math.sqrt(n);
int a = (int) n;
sqrt=(float)Math.sqrt(n);
if (temp * temp == a) {
System.out.print(temp);
} else
{
int p = 1;
int j = 1;
while(j <= d)
{
p = p * 10;
j++;
}

sqrt = (int)(sqrt * p);

System.out.print(sqrt / p);
}
}
}

No comments:

Post a Comment