The Lesson of Mathematics#572

The Lesson of Mathematics (Editorial)

The problem requires factoring the number into prime factors, that is, representing it in the form n = p_1^{a_1} \cdot p_2^{a_2} \cdot ... \cdot p_k^{a_k}, where p_1 < p_2 < ... < p_k are prime numbers. Each prime divisor p_i is printed together with its exponent a_i, if a_i > 1.

Iterate over possible divisors in increasing order, starting from . If divides , keep dividing by as long as the division is exact, and count the number of divisions . The resulting value is exactly the exponent with which appears in the factorization. After that, print if c = 1, or i^c if c > 1.

It is enough to iterate over divisors up to \sqrt{n}. If a number has no divisors in the range from to \sqrt{n}, then it is prime. Therefore, after the loop finishes, the current value of is either or a prime number. In the second case, it is the last factor of the factorization and must also be printed. There can be only one such "large" factor: the product of two factors greater than \sqrt{n} exceeds .

Example. Consider n = 3240.

The remainder n = 5 > 1 is a prime factor, so print .

Answer: 2^3*3^4*5.

Algorithm implementation

The factor function performs the factorization of into its prime factors.

void factor(int n)
{
  for (int i = 2; i <= sqrt(n); i++)
  {
    if (n % i) continue;

The number is a divisor of . In the variable , compute the power with which it appears in the factorization of .

    int c = 0;
    while (n % i == 0) n /= i, c++;

Print the factor i^c. If the power c = 1, print only . Otherwise, print the factor along with its power.

    if (c > 1) printf("%d^%d",i,c); else printf("%d",i);

If the number is not fully factorized yet (n > 1), print a multiplication sign.

    if (n > 1) printf("*");
  }

If, after completing the loop, the value of is greater than , it is a prime number.

  if (n > 1) printf("%d",n);
  printf("\n");
}

The main part of the program. Read the input number and start its factorization.

scanf("%d",&n);
factor(n);

Python implementation

import math

The factor function performs the factorization of into its prime factors.

def factor(n):
  for i in range(2, math.isqrt(n) + 1):
    if n % i: continue

The number is a divisor of . In the variable , compute the power with which it appears in the factorization of .

    c = 0
    while n % i == 0:
      n //= i
      c += 1

Print the factor i^c. If the power c = 1, print only . Otherwise, print the factor along with its power.

    if c > 1: print(i,"^",c, sep = "", end="")
    else: print(i, end="")

If the number is not fully factorized yet (n > 1), print a multiplication sign.

    if n > 1: print("*", end="")

If, after completing the loop, the value of is greater than , it is a prime number.

  if n > 1: print(n)
  else: print()

The main part of the program. Read the input number and start its factorization.

n = int(input())
factor(n)