简体   繁体   English

寻找最大值任何给定数字小于另一个给定数字的幂值

[英]Finding the max. value of power of any given number which is less than another given number

For given values 'a' and 'y' , how to find max x value such that x = a^b < y for b∈N and a>0.对于给定的值 'a' 和 'y' ,如何找到最大 x 值,使得 x = a^b < y for b∈N 和 a>0。 For example, y=14 and a = 2 is given, then x must be 8. In other words,for all values of y in [8.15] , x must be 8. Similarly, for all values of y in [9,26] , x must be 9.例如,给定 y=14 且 a = 2,则 x 必须为 8。换句话说,对于 [8.15] 中 y 的所有值,x 必须为 8。类似地,对于 [9,26] 中的所有 y 值] ,x 必须是 9。

You can use log with base a.您可以使用带有基数 a 的 log。 Such a function does not exist in <cmath> , but if you remember the formula that <cmath>中不存在这样的函数,但是如果您还记得公式

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

You can do it with cmath's log (natural logarithm) function.您可以使用 cmath 的 log(自然对数)函数来实现。

int exponent = log(y)/log(a); //truncates to the floor, just what we need.
int answer = a to the power of exponent

Quite an obvious-to-algorithmize task... Take the integer part of the base-a logaritm of y and raise a to that power:相当明显的算法任务......取底数的整数部分 - 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM