-2

对于给定的值 'a' 和 'y' ,如何找到最大 x 值使得 x = a^b < y 对于 b∈N 和 a>0。例如,给定 y=14 且 a = 2,则 x 必须为 8。换句话说,对于 [8.15] 中的所有 y 值,x 必须为 8。类似地,对于 [9,26 中的所有 y 值] , x 必须是 9。

4

2 回答 2

2

您可以将 log 与 base a 一起使用。中不存在这样的函数<cmath>,但如果你还记得那个公式

log (base a, c) = log (base e, c) / log (base e, a)

您可以使用 cmath 的 log(自然对数)函数来完成。

int exponent = log(y)/log(a); //truncates to the floor, just what we need.
int answer = a to the power of exponent
于 2012-11-07T15:22:42.633 回答
0

相当明显的算法任务......取底的整数部分 - y 的对数并将 a 提高到该次方:

#include <cmath>

int exponent = (int)(log(y) / log(a)); // base-a logarithm of y, truncated to a whole number
int x = (int)pow(a, exponent); // a raised to that power
于 2012-11-07T15:23:47.060 回答