Problem:
Initially on a notepad only one character 'A' is present. You can perform two operations on this notepad for each step:
- Copy All: You can copy all the characters present on the notepad (partial copy is not allowed).
- Paste: You can paste the characters which are copied last time.
Given a number n. You have to get exactly n 'A' on the notepad by performing the minimum number of steps permitted. Output the minimum number of steps to get n 'A'.
Example 1:
Input: 3
Output: 3
Explanation:
Intitally, we have one character 'A'.
In step 1, we use Copy All operation.
In step 2, we use Paste operation to get 'AA'.
In step 3, we use Paste operation to get 'AAA'.
Note:
- The n will be in the range [1, 1000].
思路:
要得到n个'A'可以通过如下方式得到:
- 如果n为质数,那么只能通过复制一次加上粘贴n-1次得到,总共需要n次;
- 如果n为合数,那么可以通过对n进行质因数分解,得到n所有的质因数,因为质因数不能再分解,所以总共的次数为n的所有质因数之和。
Solution (C++):
int minSteps(int n) {
if (n == 1) return 0;
if (isPrime(n)) return n;
return factorization_sum(n);
}
bool isPrime(int n) {
if (n == 2) return true;
for (int i = 2; i <= sqrt(n); ++i) {
if (n % i == 0) return false;
}
return true;
}
int factorization_sum(int n) {
vector<int> fac;
int sum = 0;
while (n > 1) {
for (int i = 2; i <= n; ++i) {
if (n % i == 0) {
fac.push_back(i);
n /= i;
break;
}
}
}
for (auto x : fac) sum += x;
return sum;
}
性能:
Runtime: 0 ms Memory Usage: 6 MB
思路:
与上面的思路类似,但是简化了分解的过程:
- 如果n是质数,则总共的次数为n次;
- 如果n是合数,则n可以通过分解成2个数的乘积,然后等于分别得到这2个数的次数之和。
Solution (C++):
int minSteps(int n) {
vector<int> dp(n+1, 0);
for (int i = 2; i <= n; ++i) {
if (isPrime(i)) dp[i] = i;
else {
for (int j = 2; j <= sqrt(n); ++j) {
if (i % j == 0) {
dp[i] = dp[j] + dp[i/j];
break;
}
}
}
}
return dp[n];
}
bool isPrime(int n) {
if (n == 2) return true;
for (int i = 2; i <= sqrt(n); ++i) {
if (n % i == 0) return false;
}
return true;
}
性能:
Runtime: 4 ms Memory Usage: 6.7 MB