Problem:
Given a number m devise an algorithm to compute its square root.
Solution:
package com.myprograms;
import java.util.Scanner;
public class SquareRootOfNumber {
int n;
public static void main(String[] args) {
SquareRootOfNumber squareRootOfNumber = new SquareRootOfNumber();
squareRootOfNumber.getTheNumber();
squareRootOfNumber.findSquareRoot();
}
public void getTheNumber(){
Scanner s = new Scanner(System.in);
System.out.println("enter the number which need to find the square root");
n = s.nextInt();
s.close();
}
public void findSquareRoot(){
double g1 = 0;
double g2 = n/2;
while(g1-g2 != 0){
g1 = g2;
g2 = (g1+n/g1)/2;
}
System.out.println("the result is: " + g2);
}
}
Output:
enter the number which need to find the square root
225
the result is: 15.0
Given a number m devise an algorithm to compute its square root.
Solution:
package com.myprograms;
import java.util.Scanner;
public class SquareRootOfNumber {
int n;
public static void main(String[] args) {
SquareRootOfNumber squareRootOfNumber = new SquareRootOfNumber();
squareRootOfNumber.getTheNumber();
squareRootOfNumber.findSquareRoot();
}
public void getTheNumber(){
Scanner s = new Scanner(System.in);
System.out.println("enter the number which need to find the square root");
n = s.nextInt();
s.close();
}
public void findSquareRoot(){
double g1 = 0;
double g2 = n/2;
while(g1-g2 != 0){
g1 = g2;
g2 = (g1+n/g1)/2;
}
System.out.println("the result is: " + g2);
}
}
Output:
enter the number which need to find the square root
225
the result is: 15.0
enter the number which need to find the square root
36
the result is: 6.0
enter the number which need to find the square root
10
the result is: 3.162277660168379
No comments:
Post a Comment