Check Power of 3 in Python

Beginner
⏱️ 10 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Number Theory

What You’ll Learn

Powers of three are numbers like 1, 3, 9, 27, 81… — each is 3^k for some whole k >= 0. The clearest check is: keep dividing by 3 while exact, and see if you finish at 1. This tutorial covers that loop, a live step tracer, worked Python examples, edge cases, and complexity.

Definition

3^k

Positive integers of form 3 to a power.

Divide by 3

While exact

n //= 3 while n % 3 == 0.

End at 1

Success

Only pure powers reduce to 1.

Avoid Logs

Float risk

Integer loop is safer than log.

Live Preview

Try 27 / 10

See each division step.

vs Power of 2

Same idea

Divisor 3 instead of 2.

Introduction

A power of three is a positive integer of the form 3^k. So 27 passes (3^3) while 6 fails — it divides by 3 once and stops at 2.

Unlike power of 2, there is no popular bitwise shortcut. Interviews usually want the integer divide-by-3 loop (and a clear rejection of n <= 0).

Why it matters?

It reinforces exact integer reasoning and pairs naturally with the power-of-2 cousin interviewers often ask next.

Key Highlights

3^k Form

1, 3, 9, 27, 81…

Divide Loop

Exact // 3 until stuck.

n > 0

Zero and negatives fail.

Prefer Integers

Skip float log checks.

In short: while divisible by 3, divide; succeed only if you reach 1.

📝 Problem & Approach

Given an integer n, decide whether it is a power of three (3^k for some k >= 0).

python
# 27 -> 27/3=9, 9/3=3, 3/3=1  -> yes
# 9  -> 9/3=3, 3/3=1           -> yes
# 6  -> 6/3=2, stop at 2       -> no
# 1  -> already 1              -> yes (3^0)

Inputs & Outputs

ItemTypeDescription
nintValue to test (must be > 0 for yes).
ReturnboolTrue when n is 3^k.
Key loopmodulo / floorwhile n % 3 == 0: n //= 3

Minimal workflow

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

Method comparison

MethodIdeaNotes
Divide by 3Peel factors until stuck; check == 1Interview default — exact
Generate 3^kMultiply up and compareGreat for listing powers
log base 3Check if log is wholeFloat rounding risk — avoid

⚡ Quick Reference

GoalPattern
Reject non-positiveif n <= 0: return False
Divisible by 3?n % 3 == 0
Peel a factorn //= 3
Successreturn n == 1
Generate nextp *= 3
vs power of 2Same loop; divisor 2 instead of 3

📋 Divide vs Generate vs Log

Same question — different reliability.

Divide loop
n //= 3

Clearest exact check

Generate
p *= 3

Best for listing powers

log3
avoid floats

Rounding can lie

vs power of 2
no & trick

Usually loop-only here

Context

When This Problem Shows Up

Reach for a power-of-three check whenever you need an exact 3^k test.

  1. Interview cousins

    Often asked right after power of 2.

  2. Factor peeling

    Practice exact integer division loops.

  3. Range filtering

    List 3^k values inside a band.

  4. Teaching float traps

    Contrast logs with integer loops.

  5. Not for “divisible by 3?”

    One % 3 check is a different problem.

Key benefit: one short loop that proves exactness without floating-point surprises.

🔮 Live Preview

Shows each division step until the value is no longer divisible by 3.

Try 9, 10, 1, and 0.

Live result
Press “Run check” to see steps.

Examples Gallery

Three complete Python programs — check 27, list powers from 1 to 20, and generate powers by multiplying. Click View Output to reveal sample console results.

📚 Getting Started

The classic divide-until-one helper.

Example 1 — Check a Single Number

Checks whether a number is exactly 3^k.

python
def is_power_of_3(n: int) -> bool:
    if n <= 0:
        return False
    while n % 3 == 0:
        n //= 3
    return n == 1


number = 27
if is_power_of_3(number):
    print(f"{number} is a power of 3.")
else:
    print(f"{number} is not a power of 3.")

How It Works

27 becomes 9, then 3, then 1. Because the final value is 1, the helper returns True.

⚡ Hunting in a Range

Reuse the helper to list nearby powers of three.

Example 2 — Powers of 3 from 1 to 20

Reuses helper function for range listing.

python
def is_power_of_3(n: int) -> bool:
    if n <= 0:
        return False
    while n % 3 == 0:
        n //= 3
    return n == 1


start, end = 1, 20
print(f"Power of 3 in the range {start} to {end}:")
for i in range(start, end + 1):
    if is_power_of_3(i):
        print(i, end=" ")

How It Works

Within 1..20 the powers are 1, 3, and 9. 27 is the next power and sits just outside this band.

Example 3 — Generate Powers by Multiplying

Build 3^k directly instead of filtering every integer.

python
print("Powers 3^k for k = 0 to 5:")
power = 1
for k in range(0, 6):
    print(f"3^{k} = {power}")
    power *= 3

How It Works

When you only need the sequence, multiplying by 3 is cheaper than testing every n in a large range.

🧠 How the Algorithm Decides

1

Require n > 0

Zero and negatives are not powers of three here.

Guard
2

Divide while divisible

While n % 3 == 0, set n = n // 3.

Loop
3

Check the leftover

n == 1 means only factors of 3 were present.

Rule
=

Return the verdict

True for 3^k, else False.

🔎 Worked Walkthrough — 27 vs 6

Compare the divide loop on a yes case and a no case.

StartStepsStops atVerdict
2727 → 9 → 3 → 11Yes
99 → 3 → 11Yes
66 → 22No
1(no division)1Yes (3^0)

Ending at 1 means every factor peeled was a 3.

Use Cases

Where power-of-three checks show up beyond the interview prompt.

1. Interview Classics

Exact integer factor peeling.

Example: is_pow3(27).

2. Range Filtering

List 3^k inside a band.

Example: 1, 3, 9 in 1..20.

3. Sequence Generation

Build powers with *= 3.

Example: Example 3.

4. Contrast With Pow2

Same loop idea, different divisor.

Example: related topic.

5. Avoiding Logs

Teach float-rounding traps.

Example: prefer // loop.

6. Next: Composite

Continue the interview chain.

Example: related CTA.

Pro Tip: say “I’ll peel factors of 3 until I can’t, then check for 1” before coding.

Advantages

Why the divide-by-3 loop works well for beginners and interviews.

  1. 1. Easy to Trace

    Dry-run 27 on paper in a few steps.

  2. 2. Exact Integers

    No float rounding surprises from logs.

  3. 3. Mirrors Power of 2

    Same pattern with a different divisor.

  4. 4. Generates Cleanly

    *= 3 builds the sequence without scanning.

Pro Tip: mention that power-of-2 has a bitwise shortcut, but power-of-3 usually stays with the loop.

Usage Tips

Small habits that keep power-of-three solutions interview-ready.

  1. 1. Guard n > 0

    Reject zero and negatives first.

  2. 2. Use Floor Division

    Prefer n //= 3 over float division.

  3. 3. Dry-Run 27 and 6

    One yes and one no seals understanding.

  4. 4. Generate When Listing

    Use *= 3 if you need the sequence itself.

  5. 5. Skip Float Logs

    Mention the trap, then use integers.

Pro Tip: sanity-check 1, 27, 6, and 0 — if those four behave, your logic is solid.

Common Pitfalls

Mistakes that commonly break power-of-three programs.

  1. 1. Accepting Zero

    0 is divisible by 3 forever in careless loops.

    → Require n > 0 before dividing.

  2. 2. Trusting log3

    Floating roots can round incorrectly.

    → Prefer the integer divide loop.

  3. 3. Stopping After One Division

    Checking only n % 3 == 0.

    → Keep dividing until you cannot.

  4. 4. Forgetting 1

    1 = 3^0 is a power of three.

    → Include 1 in yes cases.

  5. 5. Using Float Division

    n /= 3 can leave floats.

    → Use n //= 3.

Edge Cases

Handle these before claiming the check is complete.

n = 1

Yes — 3^0

Already at 1; no divisions needed.

n = 0

No for this page

n <= 0 fails immediately.

n = 6

Divisible once, then no

Stops at 2, not 1.

Negative

Not accepted

Return false here.

27

Classic yes

27 → 9 → 3 → 1.

10

Classic no

Not divisible by 3 at all.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Pure factors. A power of 3 has no prime factors other than 3.
  • Growth. Sequence: 1, 3, 9, 27, 81, 243…
  • No common bit trick. Unlike 2^k, 3^k usually uses division.
  • Bounded sets. For small ranges, precompute powers and test membership.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Prove 27

  • Trace 27 → 9 → 3 → 1
  • Confirm True

2. Reject 6

  • Show stop at 2
  • Confirm False

3. List 1..20

  • Reproduce Example 2
  • Expect 1, 3, 9

4. Generate 3^k

  • Print k = 0..5
  • Match Example 3

Notes

  • Definition: power of three means n reduces to 1 by exact division by 3.
  • Check: while n % 3 == 0, do n //= 3; then n == 1.
  • Integer-safe: the division loop avoids floating-point issues from logarithms.
  • For bounded ranges, precompute powers of 3 and check membership. Power-of-2 has a bitwise shortcut; power-of-3 usually does not.

Quick Takeaway: peel factors of 3 with integer division; succeed only if you finish at 1.

⏱️ Time and Space Complexity

ApproachTimeExtra space
Divide-by-3 loopO(log n)O(1)
Generate up to boundO(log bound)O(1) or list
Range 1..U scanO(U log U) worstO(1)

Each successful division shrinks n by a factor of 3, so the loop is logarithmic in n.

Wrap Up

🎉 Conclusion

A power of three reduces to 1 by exact repeated division by 3. Guard n > 0, loop with n //= 3 while divisible, and prefer integers over logarithms.

Practice the three examples above, then continue to composite numbers.

Divide by 3 while exact; n == 1 means power of three.

💡 Best Practices

✅ Do

  • Require n > 0
  • Use n //= 3 while divisible
  • Succeed only when leftover is 1
  • Treat 1 as yes (3^0)
  • Prefer integers over log

❌ Don’t

  • Accept 0 as a power of 3
  • Trust float log alone
  • Stop after one % 3 check
  • Use /= and create floats
  • Forget negatives fail

Key Takeaways

Knowledge Unlocked

Five things to remember about powers of three

Decide 3^k the interview-friendly way.

5
Core concepts
/ 02

Loop

n //= 3

Method
> 03

Guard

n > 0

Edges
* 04

Generate

p *= 3

Listing
O 05

Cost

O(log n)

Analysis

❓ Frequently Asked Questions

A number of the form 3^k for whole k >= 0. Examples: 1, 3, 9, 27.
Yes. 3^0 = 1.
Powers of 3 are made only of factor 3. If repeated division ends at 1, it is a pure power of 3.
This tutorial returns false for n <= 0.
Yes, same repeated-division idea; only divisor changes from 2 to 3.
Possible but floating rounding can fail for large values; integer division loop is safer.
Yes. 27 / 3 = 9, 9 / 3 = 3, 3 / 3 = 1.
No. 6 is divisible by 3 once, then stops at 2, not 1.
Not a common one. Power-of-3 usually uses the divide loop.

Did you Know? 🔊

Powers of three grow as 1, 3, 9, 27, 81... Repeated division by 3 is the clearest exact integer check for this pattern.

Continue to Composite Number

Learn how to check whether a number is composite in Python.

Composite number tutorial →

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