在固定时间长一些前n个数字?时间长、数字

2023-09-11 04:16:42 作者:喜欢哼着调调゛-  7b

在一个项目欧拉问题,我需要处理,可以有上百位的号码。我需要在今年前9个数字进行一些计算。

In a Project Euler problem I need to deal with numbers that can have hundreds of digits. And I need to perform some calculation on the first 9 digits.

我的问题是:什么是最快的方法来确定一个100位整数的前N位?最后N个数字很容易与模/余数。对于第一个数字我可以申请模100倍的数字得到的数字,或者我可以将数字转换为字符串并截断,但它们都是线性时间。有没有更好的办法?

My question is: what is the fastest possible way to determine the first N digits of a 100-digit integer? Last N digits are easy with modulo/remainder. For the first digits I can apply modulo 100 times to get digit by digit, or I can convert the number to String and truncate, but they all are linear time. Is there a better way?

推荐答案

您可以指望的位数与该功能:

You can count number of digits with this function:

(defn dec-digit-count [n]
  (inc (if (zero? n) 0
  (long (Math/floor (Math/log10 n))))))

现在我们知道有多少个数字在那里,我们想只留下第9。我们必须为划分为10 ^(数字-9),或在Clojure的数量:

Now we know how many digits are there, and we want to leave only first 9. What we have to is divide the number with 10^(digits-9) or in Clojure:

(defn first-digits [number digits]
  (unchecked-divide number (int (Math/pow 10 digits))))

和调用它:(第一位数的号码9),我认为它在固定的时间。我只是我不知道日志10 的实施。但是,它肯定快了很多,一个模/循环解决方案。

And call it like: (first-digits your-number 9) and I think it's in constant time. I'm only not sure about log10 implementation. But, it's sure a lot faster that a modulo/loop solution.

此外,还有一种更简单的解决方案。你可以简单地复制和;粘贴前9位的数量

Also, there's an even easier solution. You can simply copy&paste first 9 digits from the number.