#P10869. Walk Alone

    ID: 12912 Type: Default 1000ms 256MiB

Walk Alone

Walk Alone

You are given a number axis that contains only positive integers greater than 1. The cost of walking from a point at integer \(a\) to a point at integer \(b\) is defined as \(\mathrm{lcm}(a,b)\), where \(\mathrm{lcm}(a,b)\) is the least common multiple of \(a\) and \(b\) and is given by:

[ \mathrm{lcm}(a,b)=\frac{a\times b}{\gcd(a,b)} ]

However, no one is allowed to move to any point corresponding to an integer \(\le 1\) (because of the hatred of the integer 1). Given two integers \(a\) and \(b\) (both greater than 1), determine the minimal total cost to walk from \(a\) to \(b\). You may use intermediate stops at any integers \(>1\), and the total cost is the sum of the costs of each step.

Note: If \(a = b\), no move is needed so the cost is 0.

Observation:

  • If \(a\) divides \(b\) (or vice versa), then the direct move cost is \(\mathrm{lcm}(a,b)=\max(a,b)\), which is less than \(a+b\).
  • If \(\gcd(a,b)>1\) (and neither divides the other), one possible move is an intermediate step through a common divisor \(d\) (with \(d>1\)) so that \(d\) divides both \(a\) and \(b\). In that case, one can move from \(a\) to \(d\) at a cost \(\mathrm{lcm}(a,d)=a\) and from \(d\) to \(b\) at a cost \(\mathrm{lcm}(d,b)=b\), so the total cost is \(a+b\). The answer will be the minimum of the direct cost and this two‐step method.
  • If \(\gcd(a,b)=1\) (i.e. they are coprime), there is no common divisor greater than 1. In this case, two strategies can be considered:
    • Direct move: The cost is \(\mathrm{lcm}(a,b)=a\times b\).
    • Three–vertex path: Choose a prime factor \(p\) of \(a\) and a prime factor \(q\) of \(b\) (note that since \(a\) and \(b\) are coprime, \(p\neq q\)). Then moving \(a\to p\to q\to b\) costs: \[ \mathrm{lcm}(a,p)+\mathrm{lcm}(p,q)+\mathrm{lcm}(q,b)=a + (p \times q) + b. \] The answer in this case is the minimum between the direct cost \(a\times b\) and \(a+b+\min_{p,q}(p\times q)\), where \(p\) ranges over the prime factors of \(a\) and \(q\) over the prime factors of \(b\).

Your task is to determine the minimal total cost using these possibilities.

inputFormat

The input consists of a single line containing two integers \(a\) and \(b\) (both greater than 1), separated by a space.

outputFormat

Output a single integer representing the minimal total cost to walk from \(a\) to \(b\).

sample

2 4
4