Check Cube Number in C#

Beginner
⏱️ 9 min read
📚 Updated: May 2026
🎯 2 Code Examples
Number theory

What you’ll learn

  • What it means for an integer to be a perfect cube (n = k3).
  • A compact check using Math.Cbrt and Math.Round plus 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() and Console.WriteLine.
  • long for products like k * k * k when values might approach int limits.

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.

8
27
9 not a cube

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 = 27

Real cube root of 27 is 3, and 33 = 27.

Intuition

27
Check
3·3·3
28 Not a cube
Near
sits between 33 and 43

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.

Try -8, 0, or a non-cube such as 28.

Live result
Press “Check cube” to classify the number.

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

Pseudocode (nonnegative integer route)
function isPerfectCubeNonneg(n):  // n ≥ 0
    k ← 0
    while k * k * k < n:
        k ← k + 1
    return k * k * k = n
1

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.

c#
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.AwayFromZero

Predictable halves. Matches common math rounding when the cube root lands exactly halfway between two integers (rare here but harmless).

2

Integer scan: cubes from 1 to 50

Lists 1 8 27—no floating-point library calls. For larger num, keep cubing in long.

c#
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 * k

Widen 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

An integer n is a perfect cube if n = k^3 for some integer k. Examples: 0 = 0^3, 1 = 1^3, 8 = 2^3, 27 = 3^3, -8 = (-2)^3.
Floating-point arithmetic can be slightly off. Rounding the cube root gives a candidate k; cubing k again as a long integer proves whether n really equals k^3.
Cube roots via Pow can drift, and casting negatives with naive +0.5 tricks breaks for several values. Math.Cbrt handles negative inputs correctly; combine it with Math.Round and an integer cube check.
Yes when n is so large that it cannot be represented exactly as a double (beyond about 2^53). For very large values prefer pure integer methods or BigInteger.
Use long (or checked arithmetic) when cubing so intermediate products stay correct for typical int interview ranges.
Yes: 0 = 0^3. The programs on this page treat 0 as a perfect cube.
Increasing k until k^3 >= n uses O(n^{1/3}) steps for nonnegative n; each step is O(1) with wide arithmetic for the cube.

🔄 Input / output examples

Change inputNumber in Example 1 or widen the loop in Example 2.

nPerfect cube?k
27Yes3
-8Yes-2
28No
0Yes0

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.

Sign

Math.Cbrt on negatives

Defined for negative reals (for example Cbrt(-27) == -3). Combine with rounding plus long cubing.

Zero

n = 0

Perfect cube: 03. Example 2 starts k at 0, so it would classify 0 correctly if you extend the loop.

Overflow

k * k * k in int

Large k can overflow int before you compare. Prefer long (as in the samples).

Double

Huge integers

double cannot represent every integer past 253 exactly; switch to integer-only or BigInteger for enormous values.

⏱️ Time and space complexity

MethodTimeExtra space
Cbrt + verifyO(1) practicalO(1)
Linear k scan (nonnegative)O(n1/3) stepsO(1)
Binary search on kO(log n) iterationsO(1)

Here n is the magnitude of the input for the scan bound k ≈ n1/3.

Summary

  • Definition: n = k3 for some integer k (includes 0 and negatives).
  • Code: round Math.Cbrt(n), cube-check in long, or pure integer scan.
  • Watch-outs: float-only tests, overflow in k3, double precision limits.
Did you know?

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.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful