+ 1
Cube roots in c without using the cbrt () function
I tried to find cube root of numbers without using the cbrt() function from the math library. It only worked for the perfect cubes like 27. Please help Sample code #include<stdio.h> int main() { float n; printf("Enter a number\n"); scanf("%f",&n); for(float i=0;i<=n;i++){ if(i*i*i==n){ printf("The cube root of %.3f is %.3f\n",n,i); } } return 0; }
6 Respostas
+ 4
FunOfCoding right, and to find the cube root of 27 you use the exponent of 1/3 on 27
27^(1/3) = 3
+ 3
FunOfCoding I think you meant that you find the exponential of that number to 1/2 for square and 1/3 for cube. Multiplying will just give you half and a third of the number.
+ 2
Anyway, remember that exponent of 1/3 on 27, so pow(27, 1.0/3) is not equivalent to cbrt(27), because the rational number ⅓ is typically not equal to 1.0/3, and cbrt usually gives more accurate results
+ 2
Wanjala Stephen It is working for perfect roots because you are only searching for them in integers.
If you look closely, you are just performing a linear search in a list on integers from 0 to n
If you perform a binary search(as the numbers are already sorted) instead in set of all the real numbers between 1 to n, you can easily do fo the job in lesser time complexity of O(log n).
+ 2
A binary search takes an ordered/sorted list or array and picks the middle point or index compares it to the desired value, if it is the value then you're done. Otherwise, if the value is higher, you then repeat the process with the left half of the array. If the value is lower you repeat with the right half of the array. This cycle repeats until the correct value is found.
Here's a c++ example
https://www.sololearn.com/learn/683/?ref=app
+ 1
Michał Doruch ~ how do I implement a binary search?