C++程序:计算将数字n变为1所需的最小操作次数
假设我们有一个数字n。我们可以对它执行任意次数的以下任一操作:
当n可被2整除时,将n替换为n/2
当n可被3整除时,将n替换为2n/3
当n可被5整除时,将n替换为4n/5
我们需要计算将数字变为1所需的最小移动次数。如果不可能,则返回-1。
因此,如果输入为n = 10,则输出为4,因为使用n/2得到5,然后使用4n/5得到4,然后再次使用n/2得到2,最后再次使用n/2得到1。
步骤
为了解决这个问题,我们将遵循以下步骤:
m := 0 while n is not equal to 1, do: if n mod 2 is same as 0, then: n := n / 2 (increase m by 1) otherwise when n mod 3 is same as 0, then: n := n / 3 m := m + 2 otherwise when n mod 5 is same as 0, then: n := n / 5 m := m + 3 Otherwise m := -1 Come out from the loop return m
示例
让我们来看下面的实现,以便更好地理解:
#include <bits/stdc++.h>
using namespace std;
int solve(int n) {
int m = 0;
while (n != 1) {
if (n % 2 == 0) {
n = n / 2;
m++;
}
else if (n % 3 == 0) {
n = n / 3;
m += 2;
}
else if (n % 5 == 0) {
n = n / 5;
m += 3;
}
else {
m = -1;
break;
}
}
return m;
}
int main() {
int n = 10;
cout << solve(n) << endl;
}输入
10
输出
4
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP