In: Computer Science
Writing an nth root program in C++ using only:
#include
using namespace std;
The program must be very basic. Please don't use math sqrt or pow . For example, the 4th root of 16 is 2 because 2 * 2 * 2 * 2 = 16. The 4th root of 20 is 2 because 2 * 2 * 2 * 2 = 16 and 16 is less than 20, and 3 * 3 * 3 * 3 = 81, which is bigger than 20. Assume that the user does not input anything less than 0. The 8th root of 1679616 is 6 because 6 * 6 * 6 * 6 * 6 * 6 * 6 * 6 = 1679616.
nth root program in C++ Code:-
#include <iostream>
//including headers
using namespace std;
//function declartion globally
double now(double, double);
double nthroot(double, double);
//function definition
double nthroot(double e, double f)
{
//intialization of variables
double n(f);
double w;
double jkl;
double hgk(10e-6);
double A(e);
//assigning w with value
w = A * 0.5;
//this is jkl
jkl = (A/now(w,n-1)-w)/n;
//while loop starts
while(jkl >= hgk || jkl <= -hgk) //condition for while
loop
{
//assigning the w with the below addition for iteration
w = w + jkl;
//calling function and then calaculation and storing in jkl
variable
jkl = (A/now(w,n-1)-w)/n;
}
return w;
}
//function definition
double now(double k, double l)
{
double d(1);
//for loop
for(int j = 0;j<l;++j)
d *= k;
return d;
}
//main function starts
int main()
{
double a,b;
//values should not be negative
cout << "Enter value to find root: ";
cin >> a;
//taking inputs
cout << "Enter number of root: ";
cin >> b;
int z = nthroot(a ,b);
//storing the returned value of function in x
cout << z << endl;
//printing z the answer
return 0;
}
//end of the program
Indentation:-
PIC-1:
PIC-2:
Outputs with diiferent numbers for nth root:-
***If you have any doubt please feel free to comment...Thank You...Please UPVOTE***