determining whether a number is a square/cube
Oct 2, 2016 at 12:58pm UTC
i came across the following question:
Determine whether a given number is a square number/cube number
and have the following implementation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#include<iostream>
#include<math.h>
int isRootOrCube(double num);
int main() {
std::cout << isRootOrCube(0.027) << std::endl;
return 0;
}
int isRootOrCube(double num) {
double is_root = sqrt(num);
double is_cube = cbrt(num);
is_root = num - powl(is_root,2);
is_cube = num - powl(is_cube,3);
if ((is_root == 0) && (is_cube == 0)) return 0;
else if (is_root == 0) return 1;
else if (is_cube == 0) return 2;
else return 3;
}
the problem being with numbers like 0.027 which is a cube number (0.3*0.3*0.3) the function returns 3 as if the numbers isn't a root nor a cube number but it should return 2.
and when you put in 9 it would return 0 as if it is both a cube and square number when its only a square number and should return 1 and i cant understand where is the problem. can it be the precision ?
Oct 2, 2016 at 1:46pm UTC
There is both precision and logic at play.
Floating point math is not intuitive. The
x==y
should not be used. Websearch on that topic.
You do compute sqrt(num), which by definition is the root of num.
You do compute cbrt(num), which by definition is the cuberoot of num.
If the math were exact, you would always get 0, because logically:
* num is the square of sqrt(num)
* num is the cube of cbrt(num)
I do not think that there is any sense in isRootOrCube beyond
rational numbers :
https://en.wikipedia.org/wiki/List_of_types_of_numbers
(27/1000 is rational)
Oct 2, 2016 at 3:33pm UTC
i decided to stick to the integer only solution. is the code below good from a logic standpoint or is it possible to optimize it(for integers only).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#include<iostream>
#include<math.h>
int isRootOrCube(int num);
int main() {
std::cout << isRootOrCube(8) << std::endl;
return 0;
}
int isRootOrCube(int num) {
int is_root = sqrt(num);
int is_cube = cbrt(num);
is_root = num - pow(is_root,2);
is_cube = num - pow(is_cube,3);
if ((is_root == 0) && (is_cube == 0)) return 0;
else if (is_root == 0) return 1;
else if (is_cube == 0) return 2;
else return 3;
}
Topic archived. No new replies allowed.