Wednesday, November 6, 2013

finding cube root of a number without pow method in C!!



Below code is to find the cube root of a given integer number with out using pow math library function. Its very simple and brute force way to find the cube root. This is not the best way, but one of the way to find the cube root. The basic Idea is to find the cube of the numbers from one  and checking with the given number, if the given number is same the cube of the number, then cube number is the cube root of the number. If you need for more than 5000, jus modify the MAX_NUMBER in the code and run.


Limitations:

  • It works for only Integers
  • Its a brute force method


#include<stdio.h>
#define MAX_NUMBER 5000
int find_cuberoot(int number)
{
 int i,cube= 0;
 for(i=0;i<MAX_NUMBER;i++)
 {
   cube= i*i*i;
   if(cube==number)
     return i;
   else if(cube>number)
     break;
 }
 return 0;
}
int main()
{
 int n=0,result=0;
 printf("enter the number to find the cube root\n");
 scanf("%d",&n);
 if(n<0)
 {
  printf("enter only +ve integer value");
  return 0;
 }
 result = find_cuberoot(n);
 if(result)
  printf("cube root of %d is %d\n",n,result);
 else
  printf("not a proper value for finding the cube root\n");
}
Output:

$ ./a.out
enter the number to find the cube root
15625
cube root of 15625 is 25
$ ./a.out
enter the number to find the cube root
99
not a proper value for finding the cube root

No comments:

Popular Posts