- Check
3·3·3
Check Cube Number in C#
What you’ll learn
- What it means for an integer to be a perfect cube (
n = k3). - A compact check using
Math.CbrtandMath.Roundplus a final integer cube test, and an all-integer loop for listing cubes in a range. - Sign, zero, overflow, and floating-point caveats, plus a browser live preview.
Overview
Given an integer n, decide whether n = k3 for some integer k. One approach asks System.Math for the real cube root, rounds to the nearest whole number, then cubes that candidate in long to confirm.
Two programs
Cbrt + round + verify for one value, then a linear k scan for cubes from 1 to 50.
Live preview
Try integers in the safe JavaScript range using an integer cube test.
Fixes vs naive hacks
Always recube in integers; widen to long when multiplying.
Prerequisites
using System;, integer multiplication, and Math.Cbrt / Math.Round (Math.Cbrt is available in modern .NET).
static void Main()andConsole.WriteLine.longfor products likek * k * kwhen values might approachintlimits.
What is a perfect cube?
An integer n is a perfect cube (cube number) if n = k3 for some integer k. That includes 0 = 03 and negative examples such as -8 = (-2)3.
Do not confuse “cube number” with “multiple of 3” or “square number”—here we multiply three equal factors, not two.
Cube root idea
For real x, the equation k3 = x has a unique real cube root k. For integer n, n is a perfect cube iff that real root rounds to an integer k that still satisfies k3 = n in exact arithmetic.
n = 27Real cube root of 27 is 3, and 33 = 27.
Intuition
- Near
- sits between
33and43
Takeaway: perfect cubes spread out: 1, 8, 27, 64, …
Live preview
JavaScript safe integers only. The widget grows k until k3 ≥ |n| (after handling sign), then compares.
Algorithm
Goal: return true iff n = k3 for some integer k.
Cube-root route
Let k = round(Cbrt(n)) as a signed integer, then verify k*k*k == n using long.
Integer route
For nonnegative n, increase k from 0 until k3 ≥ n; answer yes iff equality holds.
📜 Pseudocode
function isPerfectCubeNonneg(n): // n ≥ 0
k ← 0
while k * k * k < n:
k ← k + 1
return k * k * k = n Math.Cbrt + Math.Round + integer check
Uses the real cube root (works for negative n), rounds to the nearest whole k, then confirms with integer cubing in long. Clearer and safer than only comparing floats with a tiny epsilon.
using System;
class Program
{
static bool IsCube(int number)
{
double root = Math.Cbrt(number);
long k = (long)Math.Round(root, MidpointRounding.AwayFromZero);
long cube = k * k * k;
return cube == number;
}
static void Main()
{
int inputNumber = 27;
if (IsCube(inputNumber))
{
Console.WriteLine($"{inputNumber} is a cube number.");
}
else
{
Console.WriteLine($"{inputNumber} is not a cube number.");
}
}
} Explanation
Math.Cbrt returns a double. Rounding picks a candidate integer root; only k * k * k == number proves the answer.
long cube = k * k * k;Exact check. Integer multiplication avoids “almost an integer” float surprises.
MidpointRounding.AwayFromZeroPredictable halves. Matches common math rounding when the cube root lands exactly halfway between two integers (rare here but harmless).
Integer scan: cubes from 1 to 50
Lists 1 8 27—no floating-point library calls. For larger num, keep cubing in long.
using System;
class Program
{
static bool IsCubeNumber(int num)
{
int k = 0;
while ((long)k * k * k < num)
{
k++;
}
return (long)k * k * k == num;
}
static void Main()
{
Console.WriteLine("Cube numbers in the range 1 to 50:");
for (int i = 1; i <= 50; i++)
{
if (IsCubeNumber(i))
{
Console.Write($"{i} ");
}
}
Console.WriteLine();
}
} Explanation
The loop finds the smallest k with k3 ≥ num. If num is a perfect cube, equality holds; otherwise k3 jumps past num.
(long)k * k * kWiden before multiply so the cube stays correct for bigger inputs.
Optimization
Binary search on k. For huge nonnegative n, binary-search k instead of stepping by one.
Big integers. Use System.Numerics.BigInteger when n can exceed normal fixed-width ranges.
Interview: mention sign, 0, overflow, and why you verify k3 in integers after any double step.
❓ FAQ
🔄 Input / output examples
Change inputNumber in Example 1 or widen the loop in Example 2.
| n | Perfect cube? | k |
|---|---|---|
27 | Yes | 3 |
-8 | Yes | -2 |
28 | No | — |
0 | Yes | 0 |
Edge cases and pitfalls
Trusting floats without an integer cube check is fragile; naive integer hacks on negative cube roots are easy to get wrong.
Math.Cbrt on negatives
Defined for negative reals (for example Cbrt(-27) == -3). Combine with rounding plus long cubing.
n = 0
Perfect cube: 03. Example 2 starts k at 0, so it would classify 0 correctly if you extend the loop.
k * k * k in int
Large k can overflow int before you compare. Prefer long (as in the samples).
Huge integers
double cannot represent every integer past 253 exactly; switch to integer-only or BigInteger for enormous values.
⏱️ Time and space complexity
| Method | Time | Extra space |
|---|---|---|
Cbrt + verify | O(1) practical | O(1) |
Linear k scan (nonnegative) | O(n1/3) steps | O(1) |
Binary search on k | O(log n) iterations | O(1) |
Here n is the magnitude of the input for the scan bound k ≈ n1/3.
Summary
- Definition:
n = k3for some integerk(includes0and negatives). - Code: round
Math.Cbrt(n), cube-check inlong, or pure integer scan. - Watch-outs: float-only tests, overflow in
k3,doubleprecision limits.
A nonzero integer n is a perfect cube iff in its prime factorization every exponent is a multiple of three. The cube roots of 0 and 1 are 0 and 1 themselves.
9 people found this page helpful
