14,879,456 members
1.00/5 (1 vote)
See more:
to find whether a number is a perfect cube or not .

What I have tried:

```#include <bits/stdc++.h>
using namespace std;

int iscqrt(int x)
{

double sr = cbrt(x);
return (sr - floor(sr) == 0);
}
int main() {
int n;
cin>>n;
if(iscqrt(n))
cout<<"perfect cube";
else
cout<<"no";

}```
Posted
Updated 12-Jan-19 5:39am
Richard MacCutchan 12-Jan-19 9:52am

Works fine when I run it, for both values.
Prateek Krishna 12-Jan-19 9:57am

27 is perfect cube. so it should give perfect cube as output but it is giving no .
Richard MacCutchan 12-Jan-19 11:10am

Well I ran your code and it says "perfect cube" for 27 and 216. I suspect the actual code you are running is somehow different.

Solution 1

You should take a look at what `sr -float(sr)` evaluates to. It's not zero, bet very close. On my system I get 4.44089e-16. Why would that be. This has to do with how computers represent floating point numbers (float, double, long double). In particular, some base-10 numbers cannot be represented to 100% accuracy. There is also the limitation of the precision of floating point numbers. As an example, in base-10 even 1.0/3.0 cannot be represented accurately, so the calculation (1.0/3.0)*3.0 expressed to 10 digits of precision returns 0.999999999, not 1.0. Combine those 2 things together and often times what we expect to happen when working with floating point numbers is wrong, when dealing with computers. In particular, comparison for equality, as shown here, doesn't always work as expected. In general, you'll want to know how accurate you need to be and compare within that accuracy. You might, for example, use this` return( fabs(sr - floor(sr)) < 1e-6)` instead of a comparison against 0.0
v4
KarstenK 12-Jan-19 12:41pm

Solution 2

The code works fine.

It's a bit messy and your return type for the "iscqrt" function should be a bool, not an int, but other than that, it works fine for both of your test cases and others.

Solution 3

Doubles can be funny numbers: they don't "match" well with their decimal equivalents, so they are at best an approximation to a number, albeit a very accurate approximation.
Instead of faffing with `floor`, take the cube root of the number, convert it to an integer, and compare that to the original:
```int iscqrt(int x)
{
int sr = (int) cbrt(x);
return ((int) x == sr * sr * sr);
} ```
Richard MacCutchan 12-Jan-19 11:08am

I ran OP's code and both numbers gave true result.
OriginalGriff 12-Jan-19 11:14am

Hmm. Maybe it's the compiler / library he is using?

Solution 4

Quote:
Why is it not working with n=27 and 216...

It is because `double` are "binary floating point numbers", and they they are not exact values.
Floating-point arithmetic - Wikipedia[^]
Binary Fractions and Floating Point - Binary Tutorial[^]

The solution is not to use floating point numbers like in solution 3.