Series · Pattern
Prime Numbers Triangle
Prime Numbers Triangle
SeriesSymbol pattern, solid style, size 5. Changing the rubric, style or size above re-shapes the loops — the structure stays identical while only the printed value or the cell filter changes.
Prime Numbers Triangle · output
Symbol · Solid · size 5
def nprime(k):
n = 2; found = 0
while True:
isprime = True
for d in range(2, int(n ** 0.5) + 1):
if n % d == 0: isprime = False; break
if isprime:
if found == k: return n
found += 1
n += 1
n = int(input("Enter number of rows: "))
c = 1
# Right triangle — row i prints exactly i values
for i in range(1, n + 1):
for j in range(1, i + 1):
print('*', end='')
c += 1
print()Behind the Scenes Execution
registers · line tracking · call stack · memory regions| Address | Variable | Value |
|---|---|---|
| Stack (4) | ||
| 0x200 | n | 5 |
| 0x204 | i | -1 |
| 0x208 | j | -1 |
| 0x20C | count | 0 |
| String Pool (static) (2) | ||
| 0x400000 | pool["*"] | * |
| 0x400008 | pool["\n"] | \n |
| Heap (5) | ||
| 0x3000 | grid[0] | |
| 0x3020 | grid[1] | |
| 0x3040 | grid[2] | |
| 0x3060 | grid[3] | |
| 0x3080 | grid[4] | |
Prime Numbers Triangle
Prime numbers fill the triangle: 2, 3, 5, 7, 11, … A tiny helper generates the next prime on demand. The shape logic stays untouched — only the term generator changes.
The size-5 grid
The fifteen cells hold the first fifteen primes: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47. The shape is identical to Floyd triangle; a helper supplies term number c on demand.
Off-by-one traps
An off-by-one in the helper index repeats or skips a prime, and testing divisors only up to n/2 instead of the square root still works but costs far more; the boundary k <= sqrt(n) must be inclusive.
Step by step
- Type n when the program asks.
- Use a tiny helper nprime(k) that hands back the k-th prime (0-based).
- Loop i = 1 to n, inner j = 1 to i.
- Print nprime(c - 1), then c += 1 — primes 2, 3, 5, 7, …
- Newline after the row.
Complexity
When to use it
- Primality-test practice
- Plugging a custom generator into a shape
grid[r] rows in the Heap region and the i / j / count registers on the Stack — every printed character is one write to the grid.Recommended resourcesAffiliate links · may earn us a commission