如果n是整数,如何找到| n-2 ^ k |是最小的

时间:2020-11-12 17:30:23

标签: c++ loops visual-c++ conditional-statements

我有一个要解决的问题。首先,我必须检查输入的 n (正整数)是否为3的次数,如果不是,则要找到一个数字 k ,使 | < strong> n -2 ^ k | 是最小的(如果有多个满足所有条件的 k )。我做了第一部分,但我不知道该怎么做。我认为我必须使用 else ,但是我遇到了麻烦。 (对不起,如果代码丑陋/编写得不好,我是一个初学者。)

#include <iostream>
#include <cmath>
using namespace std;

int main() {
    int n, m, countd = 0, k;
    do {
        cout << "Enter a positive integer: "; cin >> n;
    } while (n < 1);
    m = n;
    while (m % 3 == 0) {
        m /= 3;
        countd++;
    }if (m == 1) {
        cout << "3^" << countd << " = " << n << endl;
    }

    return 0;
}

0 个答案:

没有答案