Write a Java program to compute the square root of an given integer


Introduction

In this demo I have used NetBeans IDE 8.2 for debugging purpose. But you can use any java programming language compiler as per your availability..


techstudy.org

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

  1. import java.util.*;
  2. public class Javaexcercise {
  3. public static void main(String[] args)
  4. {
  5. Scanner in = new Scanner(System.in);
  6. System.out.print("Input a integer: ");
  7. int number = in.nextInt();
  8. System.out.printf("Square root of %d is: ",number);
  9. System.out.println(sqrt(number));
  10. }
  11.  
  12. private static int sqrt(int num) {
  13. if (num == 0 || num == 1) {
  14. return num;
  15. }
  16. int r = 0;
  17. int s = num;
  18. while (r <= s) {
  19. int mid = (r + s) >> 1;
  20. if (num / mid < mid) {
  21. s = mid - 1;
  22. } else {
  23. if (num / (mid + 1) <= mid) {
  24. return mid;
  25. }
  26. r = mid + 1;
  27. }
  28. }
  29. return r;
  30. }
  31. }

Result

java techstudy.org

     





Related Topics




Popular Posts