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.
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:
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:
And call it like:
(first-digits your-number 9)and I think it’s in constant time. I’m only not sure aboutlog10implementation. 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.