First N digits of a long number in constant-time?

血红的双手。 提交于 2019-12-03 17:18:38

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

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

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.

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

Maybe you can use not a long number, but tupple of two numbers: [first-digits, last-digits]. Perform operations on both of them, each time truncating to the required length (twice of the condition, 9 your case) the first at the right and the second at the left. Like

222000333 * 666000555
147|852344988184|815

222111333 * 666111555
147|950925407752|815

so you can do only two small calculations: 222 * 666 = 147[852] and 333 * 555 = [184]815

But the comment about "a ha" solution is the most relevant for Project Euler :)

In Java:

public class Main {
    public static void main(String[] args) throws IOException {
        long N = 7812938291232L;
        System.out.println(N / (int) (Math.pow(10, Math.floor(Math.log10(N)) - 8)));
        N = 1234567890;
        System.out.println(N / (int) (Math.pow(10, Math.floor(Math.log10(N)) - 8)));
        N = 1000000000;
        System.out.println(N / (int) (Math.pow(10, Math.floor(Math.log10(N)) - 8)));
    }
}

yields

781293829
123456789
100000000

It may helps you first n digits of an exponentiation

and the answer of from this question

This algorithm has a compexity of O(b). But it is easy to change it to get O(log b)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!