假設我們有一個數字n。我們任意執行這些操作之一-
當n 可被2 整除時,將n 替換為n/2
當n 可被3 整除時,將n 替換為2n/3
當n 可被5 整除時,將n 替換為4n/5
## li>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
以上是C++程式用來計算使數字n變成1所需的最小操作次數的詳細內容。更多資訊請關注PHP中文網其他相關文章!