thanks to @EricPostpischil for the answer perform long division, dividing the input number by the base and discarding the remainder. Doing this repeatedly and counting the repetitions produces the logarithm (the number of repetitions until the quotient is less than one is the greatest integer not greater than the logarithm; the answer of @pmg is also a good way to do it i thinks
即使你的示例函数也有拼写错误。看来您的意思是返回 n 的对数底 x 的整数部分,并对结果应用下限函数。要实现这一点,它必须是:
int logn(int n, int x) // n is the number, x is the base
{
if (n <= x - 1) return 0; // note: x, not r
return (1 + logn(n / x, x); // note: x, not 2 for the division
}
Even your example function has typos in it. It appears you meant for it to return the integer part of the logarithm base x of n, with a floor function applied to the result. To accomplish this it would have to be:
int logn(int n, int x) // n is the number, x is the base
{
if (n <= x - 1) return 0; // note: x, not r
return (1 + logn(n / x, x); // note: x, not 2 for the division
}
All that being said, I don't see any way of taking an arbitrary-base logarithm of a stringified number without converting it to a numeric value first. If you wanted only a base-10 logarithm, it would be possible.
发布评论
评论(3)
您需要将字符串转换为数字
You need to convert the string to a number
感谢@EricPostpischil 的回答
执行长除法,将输入数字除以基数并丢弃余数。重复执行此操作并计算重复次数即可得出对数(直到商小于 1 为止的重复次数是不大于对数的最大整数;
我认为@pmg的答案也是一个好方法
thanks to @EricPostpischil for the answer
perform long division, dividing the input number by the base and discarding the remainder. Doing this repeatedly and counting the repetitions produces the logarithm (the number of repetitions until the quotient is less than one is the greatest integer not greater than the logarithm;
the answer of @pmg is also a good way to do it i thinks
即使你的示例函数也有拼写错误。看来您的意思是返回 n 的对数底 x 的整数部分,并对结果应用下限函数。要实现这一点,它必须是:
话虽这么说,我看不出有任何方法可以在不首先将其转换为数值的情况下对字符串化数字取任意基对数。如果您只想要一个以 10 为底的对数,这是可能的。
Even your example function has typos in it. It appears you meant for it to return the integer part of the logarithm base x of n, with a floor function applied to the result. To accomplish this it would have to be:
All that being said, I don't see any way of taking an arbitrary-base logarithm of a stringified number without converting it to a numeric value first. If you wanted only a base-10 logarithm, it would be possible.