檢查一個數字能否表示為 C++ 中的冪
這裡,我們將檢查是否可以表示一個數字為冪,如 ab。假設有一個數字 125。這可以表示為 53。另一個數字 91 無法表示為某個整數值的冪。
演算法
isRepresentPower(num): Begin if num = 1, then return true for i := 2, i2 <= num, increase i by 1, do val := log(a)/log(i) if val – int(val) < 0.0000000001, then return true done return false End
示例
#include<iostream>
#include<cmath>
using namespace std;
bool isRepresentPower(int num) {
if (num == 1)
return true;
for (int i = 2; i * i <= num; i++) {
double val = log(num) / log(i);
if ((val - (int)val) < 0.00000001)
return true;
}
return false;
}
int main() {
int n = 125;
cout << (isRepresentPower(n) ? "Can be represented" : "Cannot be represented");
}輸出
Can be represented
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP