使用 C++ 最小化幂的和为 n 的幂的项数。
问题表述
给定两个正整数 N 和 X。任务是用 X 的幂表达 N(X0 + X1 +…..+ Xn),使得 X 的幂的个数最少。
打印用于使和等于 N 的 N 的最小幂数。
如果 N = 15 且 X = 3,那么我们需要 3 个“3”的幂,如下所示 −
15 = (32 + 31 + 31)
算法
使用以下公式计算最终结果 −
1. If x = 1, then answer will be n only (n = 1 + 1 +…. n times)s 2. Any number n can be expressed as, n = x * a + b where 0 −= b −= x-1. Now since b is between 0 to x – 1, then b should be expressed as sum of x0 b times
示例
#include <iostream>
using namespace std;
int minNumOfPower(int n, int x){
if (x == 1) {
return n;
}
int result = 0;
while (n > 0) {
result = result + (n % x);
n = n / x;
}
return result;
}
int main(){
int n = 15;
int x = 3;
cout << "Minimum number of powers = " <<
minNumOfPower(15, 3) << endl;
return 0;
}输出
在编译并执行以上程序时,会生成以下输出 −
Minimum number of powers = 3
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP