-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
PerfectCubeChecker.cs
60 lines (54 loc) · 1.55 KB
/
PerfectCubeChecker.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
using System;
namespace Algorithms.Numeric;
/// <summary>
/// A perfect cube is an element of algebraic structure that is equal to the cube of another element.
/// </summary>
public static class PerfectCubeChecker
{
/// <summary>
/// Checks if a number is a perfect cube or not.
/// </summary>
/// <param name="number">Number to check.</param>
/// <returns>True if is a perfect cube; False otherwise.</returns>
public static bool IsPerfectCube(int number)
{
if (number < 0)
{
number = -number;
}
var cubeRoot = Math.Round(Math.Pow(number, 1.0 / 3.0));
return Math.Abs(cubeRoot * cubeRoot * cubeRoot - number) < 1e-6;
}
/// <summary>
/// Checks if a number is a perfect cube or not using binary search.
/// </summary>
/// <param name="number">Number to check.</param>
/// <returns>True if is a perfect cube; False otherwise.</returns>
public static bool IsPerfectCubeBinarySearch(int number)
{
if (number < 0)
{
number = -number;
}
int left = 0;
int right = number;
while (left <= right)
{
int mid = left + (right - left) / 2;
int midCubed = mid * mid * mid;
if (midCubed == number)
{
return true;
}
else if (midCubed < number)
{
left = mid + 1;
}
else
{
right = mid - 1;
}
}
return false;
}
}