In: Computer Science
*Code in C*
Write a function that checks if a number is a perfect cube.
Write another function that calculates the integer cubic root.
Under the main program:
Solution :-
Here in this problem, we need to find whether the number that will be provided to us by the user is a perfect cube and also the cube root of the number if the number has an integer cube root.
In the C program written below, there is a function called isperfectcube ( int ) to find if the number that is given as input is a perfect cube or not, hence returns 0 or 1 accordingly. 0 if the number is not a perfect cube and 1 if it is a perfect cube.
The function uses binary search whose start is 1 and the end is the number that is given as input in the main function.
Now using the while loop we are implementing the binary search that is shown below.
The function cuberoot ( int ), uses the same concept that is binary search to find the cuberoot of the number.
The program with both the function is shown below.
#include <stdio.h> // for the standard input and output stream
int isperfectcube(int n) // function to check whether the number is a perfect cube or not using binary search.
{
int start = 1, end = n; // initializing start and the end of the search.
int mid = (start + end)/2; // the middle of the searching range is calculated.
while (start <= end)
{
if ((mid * mid * mid) == n)
{
return 1; // returning is the mid is equal to the cube root.
}
if((mid * mid * mid) > n)
end = mid - 1;
else
start = mid + 1;
mid = (start + end)/2;
}
return 0;
}
int cuberoot (int n) // function to search the cube root if there exist one using binary search.
{
int start = 1, end = n;
int mid = (start + end)/2;
while (start <= end)
{
if ((mid * mid * mid) == n)
{
return mid;
}
if((mid * mid * mid) > n)
end = mid - 1;
else
start = mid + 1;
mid = (start + end)/2;
}
return 0;
}
int main()
{
int number;
printf("Enter the number : ");
scanf("%d", & number);
if(isperfectcube(number))
{
printf("The number is a perfect cube.\n");
int croot = cuberoot(number);
printf("The cube root of the number %d is %d", number, croot);
}
else
{
printf("The number is not a perfect cube.");
}
return 0;
}