PHP Program - Square Root of a Number


Advertisements

If a number is multiplied by itself ($$n*n$$), the final number will be the square of that number and finding the square root of a number is inverse operation of squaring the number. If x is the square root of y, it can be expressed as below:

$$x = \sqrt{y}$$

Alternatively, it can also be expressed as:

$$x^2 = y$$

Example: Using sqrt() function of PHP <cmath> header file

The sqrt() function of PHP <cmath> header file can be used to return square root of a number.

#include <iostream>
#include <cmath>
using namespace std;

int main() {
	double x = 16;
	double y = 25;

	double x1 = sqrt(x);
	double y1 = sqrt(y);
	cout<<"Square root of "<<x<<" is "<<x1<<"\n";
	cout<<"Square root of "<<y<<" is "<<y1<<"\n";
	return 0;
}

Output

Square root of 16.0 is 4.0
Square root of 25.0 is 5.0

Example: Using pow() function of PHP <cmath> header file

The pow() function of PHP <cmath> header file can also be used to calculate square root of a number.

#include <iostream>
#include <cmath>
using namespace std;

int main() {
	double x = 16;
	double y = 25;

	double x1 = pow(x, 0.5);
	double y1 = pow(y, 0.5);
	cout<<"Square root of "<<x<<" is "<<x1<<"\n";
	cout<<"Square root of "<<y<<" is "<<y1<<"\n";
	return 0;
}

Output

Square root of 16.0 is 4.0
Square root of 25.0 is 5.0

Advertisements