morry2341

squrt_Binaryway

Apr 20th, 2023
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.86 KB | None | 0 0
  1. package Appendix_B;
  2.  
  3. public class B3_BinarySearch {
  4.  
  5. public static double sqrt(int n){
  6.  
  7.  
  8. long left = 1;
  9. long right = n;
  10. while(left <= right){
  11. long mid = left + (right - left)/2; //StackOverflow vermeiden
  12. if(mid*mid == n){
  13. left = (int)mid; //mid ist das gesuchte Wurzel
  14. break;
  15. } else if (mid*mid > n) {
  16. right = mid- 1; //rechte Hälfte des Arrays nicht mehr berücksichtigen
  17. } else {
  18. left = mid + 1; //die Suche geht weiter
  19.  
  20. }
  21. }
  22.  
  23. return (int) left;
  24. }
  25.  
  26. public static void main(String[] args) {
  27. System.out.println("Enter any number ");
  28. int n = new java.util.Scanner(System.in).nextInt();
  29. System.out.println("Moment der Wahrheit: " + sqrt(n));
  30. }
  31.  
  32. }
Advertisement
Add Comment
Please, Sign In to add comment