Check Power of 3 in JavaScript

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

What you’ll learn

  • Which numbers are powers of three: 1, 3, 9, 27, 81, …
  • The divide-by-3 loop: peel factors of 3 until you stop; you should land on 1 only for pure powers.
  • Two JavaScript programs: one number (sample 27) and a 1–20 list (1 3 9).
  • A live preview that shows each division step, plus usual edge cases.

Overview

Picture multiplying by 3 again and again: 1 → 3 → 9 → 27 → 81 → … Any value on that train is a power of 3. To test a mystery number n, run the movie backward: while n is divisible by 3, replace n with n / 3. If you end exactly at 1, the original was on the train. If you stop on something like 2 or 4, it was not.

No heavy math library

Only % and / on integers—easy to read in an exam.

Live preview

Watch 27 → 9 → 3 → 1 (or try a non-example like 15).

Range drill

Between 1 and 20, only 1, 3, 9 qualify (the next would be 27).

Prerequisites

Integer division and the remainder operator % (“mod”).

  • #include <stdio.h>, while loops, and if.
  • Knowing that 27 % 3 == 0 means “27 divides evenly by 3.”

What is a power of 3?

A power of three is any whole number 3k with k ≥ 0. The first few are 1, 3, 9, 27, 81, …

There is no secret second prime hiding inside those values—only threes (and the empty product for k = 0, which gives 1). That is why stripping factors of 3 works as a test.

Why repeated division works

If n = 3k and k > 0, then n is a multiple of 3. Dividing once gives 3k − 1. Repeat until you reach 30 = 1. If at any point n is not divisible by 3 but still bigger than 1, then n had some other prime factor—so it was not a pure power of 3.

After the loop

Stopping when n % 3 != 0 leaves a “core” integer. That core is 1 exactly for powers of 3 (among positive n).

Quick examples

27 Yes
Peel 3s
27 → 9 → 3 → 1
15 No
Peel 3s
15 → 5 (stuck; 5 is not 1)
1 Yes
Because
30 = 1; nothing to divide.

Live preview

Mirrors the C logic: reject non-positive values, then divide by 3 while the remainder is 0. Uses JavaScript safe integers only.

Try 9, 10, or 1. Cap keeps very large inputs from slowing the tab.

Live result
Press “Run check” to see the steps.

Algorithm

Goal: return true iff positive n equals 3k for some integer k ≥ 0.

Reject n <= 0

Powers of three here are positive counting numbers.

Strip factors of 3

While n % 3 == 0, replace n with n / 3.

Finish

If the remaining value is 1, return true; otherwise false.

📜 Pseudocode

Pseudocode
function isPowerOfThree(n):
    if n <= 0:
        return false
    while n mod 3 = 0:
        n ← n / 3
    return n = 1
1

Check a single number

Uses boolean return values and the same divide-by-3 logic. The guard n <= 0 keeps edge cases clear and predictable.

JavaScript
function isPowerOf3(n) {
  if (n <= 0) {
    return false;
  }

  while (n % 3 === 0) {
    n /= 3;
  }

  return n === 1;
}

const number = 27;
if (isPowerOf3(number)) {
  console.log(number + " is a power of 3.");
} else {
  console.log(number + " is not a power of 3.");
}
Try it Yourself

Explanation

For 27, the loop runs three times: 27 → 9 → 3 → 1. Then 1 % 3 is not zero, so the loop stops and n == 1 succeeds.

2

Powers of 3 from 1 to 20

Same helper as Example 1, then scan each value in the range and collect matches.

JavaScript
function isPowerOf3(n) {
  if (n <= 0) {
    return false;
  }

  while (n % 3 === 0) {
    n /= 3;
  }

  return n === 1;
}

const start = 1;
const end = 20;
const values = [];

for (let i = start; i <= end; i++) {
  if (isPowerOf3(i)) {
    values.push(String(i));
  }
}

console.log("Power of 3 in the range " + start + " to " + end + ":");
console.log(values.join(" "));
Try it Yourself

Explanation

27 would be next in the sequence, but it is greater than 20, so the printed line stops at 9.

Notes

Max exponent in int. For 32-bit int, the largest power of 3 that still fits is 319 = 1 162 261 467 (approximately). For long long, you can go further before overflow.

Alternate form. Some solutions precompute allowed values in a set or use a ceiling constant loop; the division loop remains the standard interview answer.

Compare: see the power of 2 page for the bitwise constant-time trick special to two.

❓ FAQ

It is a whole number you get by starting at 1 and multiplying by 3 over and over (or by writing 3^k for a whole number k). Examples: 1, 3, 9, 27, 81&hellip; Non-examples: 2, 6, 10, 12.
Yes. By convention 3^0 = 1, so the list usually begins with 1. The programs on this page return true for 1.
If n = 3^k with k &gt; 0, then n is divisible by 3. Peel off one factor of 3 at a time. When you cannot divide evenly anymore, you should be left with exactly 1 if and only if n was a pure power of 3.
This page treats powers of three as positive counting numbers. The code returns false for n &lt;= 0.
Same story (repeated division), different divisor. Powers of two also have a famous bitwise shortcut; powers of three are usually taught with the divide-by-3 loop first.
You can compare log(n)/log(3) to an integer in theory, but floating rounding breaks exact checks for large integers. The integer loop is safer for interviews unless the problem guarantees tiny n.

🔄 Input / output examples

Example 1 uses a fixed number. In practice, take input from prompt (browser) or readline (Node.js).

Input numberTypical line (Example 1)
2727 is a power of 3.
1010 is not a power of 3.
11 is a power of 3.
00 is not a power of 3.

Edge cases

Watch input validation and overflow on huge theoretical inputs.

n = 1

No divisions needed

The while body never runs; n == 1 returns true.

Multiples of 3

Not every multiple qualifies

6 divides by 3 once to 2, which is not 1, so 6 fails.

Overflow

Very large n

Repeated division is safe, but if you multiply to build candidates, use a wide type so you do not overflow int.

⏱️ Time and space complexity

ApproachTime (single n)Extra space
Divide-by-3 loopO(log3 n) divisions (same class as O(log n))O(1)
Scan [1, U]O(U log U) in the worst caseO(1)

Summary

  • Idea: powers of 3 are 1, 3, 9, 27, … — only threes in the prime factorization.
  • Code: reject n <= 0, then while (n % 3 == 0) n /= 3;, then check n == 1.
  • Contrast: power-of-2 has a bitwise shortcut; power-of-3 is usually the division loop first.
Did you know?

Powers of three grow a bit faster than powers of two: 1, 3, 9, 27, 81… In math puzzles and some algorithms, “keep dividing by 3” is the clearest way to test whether a positive integer is exactly 3k.

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.

8 people found this page helpful