PHP Power of 3 Program

Beginner
5 min read
Updated: Oct 2026
3 programs
Live preview

What Is a Power of 3?

A positive integer is a power of 3 when it equals 3k for some integer k ≥ 0.

Remember
Powers of 3: 1, 3, 9, 27, 81, 243, ...

  1 = 3⁰
  3 = 3¹
  9 = 3²
 27 = 3³

Not: 0, 2, 6, 12, 18, negatives
nReasonPower of 3?
2727 → 9 → 3 → 1Yes
130Yes
1212 / 3 = 4 (stops at 4)No
0Not positiveNo

How to Check a Power of 3 in PHP

Four clear steps — then pick a divide-down loop or a multiply-up sequence.

  1. Require $n > 0.
  2. While $n is divisible by 3, set $n = intdiv($n, 3).
  3. If the remaining value is 1, it was a power of three.
  4. Or start at 1 and multiply by 3 until you match or pass $n.
MethodIdeaTimeBest for
Divide by 3Peel factors of 3 until leftover is not divisible by 3O(log n)Default interview answer
Multiply upBuild 1, 3, 9, … until ≥ nO(log n)Showing the sequence explicitly

Pseudocode

Pseudocode
function IsPowerOfThree(n):
    if n <= 0: return false

    while n % 3 == 0:
        n = n / 3

    return n == 1

Cheat Sheet

Keep these facts handy while writing the program.

TopicDetail
TestDivide by 3 while possible; end at 1
13^0 — yes
0 / negativesNot powers of three here
Avoid logFloating point can misclassify
vs Power of 2No simple $n & ($n - 1) style trick
Classic checks27 yes; 12 no; 9 yes

Live Preview

Enter an integer to see each divide-by-3 step and the final verdict.

Whole numbers only. Tap a chip or type a value.

Result
n = 27
Steps: 27 → 9 → 3 → 1
27 is a power of 3

Worked Walkthrough — n = 27

Divide by 3 whenever the remainder is zero; stop when you cannot.

Calculation
27 % 3 === 0 → intdiv(27, 3) = 9
 9 % 3 === 0 → intdiv(9, 3)  = 3
 3 % 3 === 0 → intdiv(3, 3)  = 1

1 % 3 !== 0 → stop
remaining === 1 → power of 3

Counterexample n = 12:
  intdiv(12, 3) = 4
  4 % 3 !== 0 → stop at 4 ≠ 1 → not a power of 3

PHP Programs

Start with the divide loop — it is the clearest exact check. List matches in a range, then generate powers by multiplying.

Example 1 — Divide-by-3 Loop

Keep dividing while divisible by 3; success means you finish at 1.

PHP
<?php
function isPowerOfThree(int $n): bool {
    if ($n <= 0) {
        return false;
    }

    while ($n % 3 === 0) {
        $n = intdiv($n, 3);
    }

    return $n === 1;
}

$number = 27;
if (isPowerOfThree($number)) {
    echo $number . " is a power of 3\n";
} else {
    echo $number . " is not a power of 3\n";
}
?>

How It Works

  1. Reject $n <= 0 immediately.
  2. While $n % 3 === 0, divide with intdiv($n, 3) — peel off factors of three.
  3. When the loop stops, $n is not divisible by 3 anymore.
  4. If that leftover is 1, every factor was a 3.
  5. Any other leftover (2, 4, 5, …) means extra prime factors remain.

Example 2 — Powers of 3 from 1 to 20

Reuse the helper and print every match on one line.

PHP
<?php
function isPowerOfThree(int $n): bool {
    if ($n <= 0) {
        return false;
    }

    while ($n % 3 === 0) {
        $n = intdiv($n, 3);
    }

    return $n === 1;
}

echo "Powers of 3 from 1 to 20:\n";
$line = "";
for ($i = 1; $i <= 20; $i++) {
    if (isPowerOfThree($i)) {
        $line .= $i . " ";
    }
}
echo trim($line) . "\n";
?>

How It Works

  1. Outer loop visits every integer from 1 to 20.
  2. Each value is tested with the same isPowerOfThree helper.
  3. Matches are collected into one space-separated line.
  4. Only 1, 3, 9 appear in this band (27 is past 20).
  5. Keeping the helper pure makes range listing easy.

Example 3 — Generate Powers

Build 3k by multiplying a running power by 3.

PHP
<?php
$kMax = 5;
$power = 1;

echo "Powers 3^k for k = 0 to " . $kMax . ":\n";
for ($k = 0; $k <= $kMax; $k++) {
    echo "3^" . $k . " = " . $power . "\n";
    $power *= 3;
}
?>

How It Works

  1. Start at $power = 1 (that is 3^0).
  2. Print the current power, then multiply by 3 for the next exponent.
  3. No floating-point check is needed — you build exact powers.
  4. Change $kMax to print a longer list.
  5. The same multiply idea can also test a number: grow until you match or pass $n.

Edge Cases & Pitfalls

Check these before calling the solution done.

1

30 counts

1 is a power of three. The divide loop never runs and returns true.

0

Not a power of 3

Guard with $n > 0 before dividing.

Multiples

6, 12, 18…

Divisible by 3 once is not enough — leftover must be 1.

log

Prefer exact math

Avoid log for the interview solution; use intdiv loops.

Time and Space Complexity

ProgramTimeExtra space
Divide-by-3 loopO(log n)O(1)
Range listingO(R log R) for range size RO(1)
Generate powersO(kMax)O(1)

Each divide or multiply step shrinks or grows by a factor of 3, so iterations follow the exponent.

Key Takeaways

  • Definition: n = 3k for some k ≥ 0.
  • Loop: divide by 3 while possible; success if you land on 1.
  • Alt: multiply 1 by 3 until you reach or pass n.
  • Test set: 1 → yes; 27 → yes; 12 → no; 0 → no.

One line: keep dividing by 3; if you finish at 1, n is a power of three.

Frequently Asked Questions

A positive integer of the form 3^k for some integer k ≥ 0. Examples: 1, 3, 9, 27, 81.
While n is divisible by 3, divide with intdiv($n, 3). If you end at 1, n is a power of three. Or multiply a running power by 3 until it reaches or passes n.
Yes. 1 = 3^0.
Logarithms use floating point and can misclassify near powers. Exact integer divide or multiply loops are safer for interviews.
Both the divide loop and the multiply-up approach are O(log n) and use O(1) extra space.

Next: Prime Factors

Find the prime factorization of a number.

Prime factors tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

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