TheThugger
TheThugger

Reputation: 33

How to evaluate if a number is cube

I'm trying to calculate the cube root of a number to check if it's a perfect cube. Unfortunately the .NET Framework has no built-in function for that. So in order to calculate the cube root of a number I have to use the Math.Pow function:

double cubeRoot = Math.Pow(125, (double)1 / 3);

When I try to evaluate if the cube root is an integer it outputs false, yet 125 is a perfect cube:

Console.WriteLine(cubeRoot % 1 == 0);

How can I overcome this issue?

Upvotes: 1

Views: 1007

Answers (1)

phuclv
phuclv

Reputation: 41932

You need to round and check if the cube of the cube root is equal to the original value

double input = 125;
double cubeRoot = Math.Pow(input, 1.0/3.0);
double c = Math.Round(cubeRoot);
Console.WriteLine(c*c*c == input);

Note that Math.Pow(input, 1.0/3.0) is not the most accurate way to calculate cube root because 1.0/3.0 is not exactly representable in binary (and decimal). But since we're rounding the result to int anyway, the output will not be affected

.NET Core 2.1 added Math.Cbrt(double) which can be used to get a correct result in double precision, though I'm not sure if it's faster than the Math.Pow() solution or not

Upvotes: 8

Related Questions