Prime factorization

Every whole number greater than 1 has exactly one factorization into primes. Your program finds it with trial division up to the square root.

What to build

A program that prints the prime factorization of each given number.

Requirements

  • Read t, then t numbers n, one per line.
  • For each n print its prime factors in increasing order, written p^e when the exponent e is greater than 1 and p when it is 1, joined by *, such as 2^3 * 3^2 * 5.
  • For n = 1 print 1.

Input

The first line has t. Each of the next t lines has one number n.

Output

One line for each n.

Constraints

1 ≤ t ≤ 5; 1 ≤ n ≤ 10 to the power 12.

Example

Input:

3
360
17
1

Output:

2^3 * 3^2 * 5
17
1

Why it works

Dividing out the smallest divisor first guarantees that every divisor found is prime, since a composite divisor would have had its prime factors removed earlier. A leftover above 1 after d passes the square root of the remaining number must be prime, because a composite one would have a divisor not above its square root.

Examples

Example 1 · Input
3
360
17
1
Expected output
2^3 * 3^2 * 5
17
1
Example 2 · Input
2
100
97
Expected output
2^2 * 5^2
97

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Divide out each divisor d starting at 2 as long as d divides n, counting how many times.

Hint 2

Stop when d * d > n; whatever is left above 1 is itself a prime factor.

Hint 3

Write p^e when the exponent e is more than 1, and just p when it is 1. Join the parts with ` * `. For n = 1 print 1.

Solution

Show one correct solution (try it yourself first)
t = int(input())
for _ in range(t):
    n = int(input())
    parts = []
    d = 2
    while d * d <= n:
        e = 0
        while n % d == 0:
            n //= d
            e += 1
        if e == 1:
            parts.append(str(d))
        elif e > 1:
            parts.append(f"{d}^{e}")
        d += 1
    if n > 1:
        parts.append(str(n))
    print(" * ".join(parts) if parts else "1")

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Divisibility, primes and the gcd →