简体   繁体   中英

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. 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.

You can use log with base a. Such a function does not exist in <cmath> , but if you remember the formula that

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

You can do it with cmath's log (natural logarithm) function.

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:

#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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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