开发者

How to solve Euler Project Prblem 303 faster?

开发者 https://www.devze.com 2023-04-01 22:55 出处:网络
The problem is: For a positive integer n, define f(n) as the least positive multiple of n that, written in base 10, uses only digits ≤ 2.

The problem is:

For a positive integer n, define f(n) as the least positive multiple of n that, written in base 10, uses only digits ≤ 2.

开发者_开发百科

Thus f(2)=2, f(3)=12, f(7)=21, f(42)=210, f(89)=1121222.


To solve it in Mathematica, I wrote a function f which calculates f(n)/n :

f[n_] := Module[{i}, i = 1; 
While[Mod[FromDigits[IntegerDigits[i, 3]], n] != 0, i = i + 1]; 
Return[FromDigits[IntegerDigits[i, 3]]/n]]

The principle is simple: enumerate all number with 0, 1, 2 using ternary numeral system until one of those number is divided by n.

It correctly gives 11363107 for 1~100, and I tested for 1~1000 (calculation took roughly a minute, and gives 111427232491), so I started to calculate the answer of the problem.

However, this method is too slow. The computer has been calculating the answer for two hours and hasn't finished computing.

How can I improve my code to calculate faster?


hammar's comment makes it clear that the calculation time is disproportionately spent on values of n that are a multiple of 99. I would suggest finding an algorithm that targets those cases (I have left this as an exercise for the reader) and use Mathematica's pattern matching to direct the calculation to the appropriate one.

f[n_Integer?Positive]/; Mod[n,99]==0  :=  (*  magic here *)
f[n_] := (* case for all other numbers *) Module[{i}, i = 1;
 While[Mod[FromDigits[IntegerDigits[i, 3]], n] != 0, i = i + 1];
 Return[FromDigits[IntegerDigits[i, 3]]/n]]

Incidentally, you can speed up the fast easy ones by doing it a slightly different way, but that is of course a second-order improvement. You could perhaps set the code up to use ff initially, breaking the While loop if i reaches a certain point, and then switching to the f function you have already provided. (Notice I'm returning n i not i here - that was just for illustrative purposes.)

ff[n_] := 
 Module[{i}, i = 1; While[Max[IntegerDigits[n i]] > 2, i++]; 
  Return[n i]]

Table[Timing[ff[n]], {n, 80, 90}]

{{0.000125, 1120}, {0.001151, 21222}, {0.001172, 22222}, {0.00059, 
  11122}, {0.000124, 2100}, {0.00007, 1020}, {0.000655, 
  12212}, {0.000125, 2001}, {0.000119, 2112}, {0.04202, 
  1121222}, {0.004291, 122220}}

This is at least a little faster than your version (reproduced below) for the short cases, but it's much slower for the long cases.

Table[Timing[f[n]], {n, 80, 90}]

{{0.000318, 14}, {0.001225, 262}, {0.001363, 271}, {0.000706, 
 134}, {0.000358, 25}, {0.000185, 12}, {0.000934, 142}, {0.000316, 
 23}, {0.000447, 24}, {0.006628, 12598}, {0.002633, 1358}}


A simple thing that you can do to is compile your function to C and make it parallelizable.

Clear[f, fCC]
f[n_Integer] := f[n] = fCC[n]
fCC = Compile[{{n, _Integer}}, Module[{i = 1},
   While[Mod[FromDigits[IntegerDigits[i, 3]], n] != 0, i++];
   Return[FromDigits[IntegerDigits[i, 3]]]],
  Parallelization -> True, CompilationTarget -> "C"];

Total[ParallelTable[f[i]/i, {i, 1, 100}]] 
(* Returns 11363107 *)

The problem is that eventually your integers will be larger than a long integer and Mathematica will revert to the non-compiled arbitrary precision arithmetic. (I don't know why the Mathematica compiler does not include a arbitrary precision C library...)

As ShreevatsaR commented, the project Euler problems are often designed to run quickly if you write smart code (and think about the math), but take forever if you want to brute force it. See the about page. Also, spoilers posted on their message boards are removed and it's considered bad form to post spoilers on other sites.


Aside:

You can test that the compiled code is using 32bit longs by running

In[1]:= test = Compile[{{n, _Integer}}, {n + 1, n - 1}];

In[2]:= test[2147483646]
Out[2]= {2147483647, 2147483645}

In[3]:= test[2147483647]
During evaluation of In[53]:= CompiledFunction::cfn: Numerical error encountered at instruction 1; proceeding with uncompiled evaluation. >>
Out[3]= {2147483648, 2147483646}

In[4]:= test[2147483648]
During evaluation of In[52]:= CompiledFunction::cfsa: Argument 2147483648 at position 1 should be a machine-size integer. >>
Out[4]= {2147483649, 2147483647}

and similar for the negative numbers.


I am sure there must be better ways to do this, but this is as far as my inspiration got me.

The following code finds all values of f[n] for n 1-10,000 except the most difficult one, which happens to be n = 9999. I stop the loop when we get there.

ClearAll[f];
i3 = 1;
divNotFound = Range[10000]; 
While[Length[divNotFound] > 1, 
  i10 = FromDigits[IntegerDigits[i3++, 3]];
  divFound = Pick[divNotFound, Divisible[i10, divNotFound]];
  divNotFound = Complement[divNotFound, divFound];
  Scan[(f[#] = i10) &, divFound]
] // Timing

Divisible may work on lists for both arguments, and we make good use of that here. The whole routine takes about 8 min.

For 9999 a bit of thinking is necessary. It is not brute-forceable in a reasonable time.

Let P be the factor we are looking for and T (consisting only of 0's, 1's and 2's) the result of multiplication P with 9999, that is,

9999 P = T

then

P(10,000 - 1) = 10,000 P - P = T

 ==> 10,000 P = P + T

Let P1, ...PL be the digits of P, and Ti the digits of T then we have

How to solve Euler Project Prblem 303 faster?

The last four zeros in the sum originate of course from the multiplication by 10,000. Hence TL+1,...,TL+4 and PL-3,...,PL are each others complement. Where the former only consists of 0,1,2 the latter allows:

last4 = IntegerDigits[#][[-4 ;; -1]] & /@ (10000 - FromDigits /@ Tuples[{0, 1, 2}, 4])

==> {{0, 0, 0, 0}, {9, 9, 9, 9}, {9, 9, 9, 8}, {9, 9, 9, 0}, {9, 9, 8, 9}, 
     {9, 9, 8, 8}, {9, 9, 8, 0}, {9, 9, 7, 9}, ..., {7, 7, 7, 9}, {7, 7, 7, 8}}

There are only 81 allowable sets, with 7's, 8's, 9's and 0's (not all possible combinations of them) instead of 10,000 numbers, a speed gain of a factor of 120.

One can see that P1-P4 can only have ternary digits, being the sum of ternary digit and naught. You can see there can be no carry over from the addition of T5 and P1. A further reduction can be gained by realizing that P1 cannot be 0 (the first digit must be something), and if it were a 2 multiplication with 9999 would cause a 8 or 9 (if a carry occurs) in the result for T which is not allowed either. It must be a 1 then. Two's may also be excluded for P2-P4.

Since P5 = P1 + T5 it follows that P5 < 4 as T5 < 3, same for P6-P8. Since P9 = P5 + T9 it follows that P9 < 6, same for P10-P11

In all these cases the additions don't need to include a carry over as they can't occur (Pi+Ti always < 8). This may not be true for P12 if L = 16. In that case we can have a carry over from the addition of the last 4 digits . So P12 <7. This also excludes P12 from being in the last block of 4 digits. The solution must therefore be at least 16 digits long.

Combining all this we are going to try to find a solution for L=16:

Do[
  If[Max[IntegerDigits[
      9999 FromDigits[{1, 1, 1, 1, i5, i6, i7, i8, i9, i10, i11, i12}~
         Join~l4]]
     ] < 3, 
   Return[FromDigits[{1, 1, 1, 1, i5, i6, i7, i8, i9, i10, i11, i12}~Join~l4]]
  ], 
  {i5, 0, 3}, {i6, 0, 3}, {i7, 0, 3}, {i8, 0, 3}, {i9, 0, 5}, 
  {i10, 0, 5}, {i11, 0, 5}, {i12, 0, 6}, {l4,last4}
 ] // Timing

==> {295.372, 1111333355557778}

and indeed 1,111,333,355,557,778 x 9,999 = 11,112,222,222,222,222,222

We could have guessed this as

f[9] = 12,222
f[99] = 1,122,222,222
f[999] = 111,222,222,222,222

The pattern apparently being the number of 1's increasing with 1 each step and the number of consecutive 2's with 4.

With 13 min, this is over the 1 min limit for project Euler. Perhaps I'll look into it some time soon.


Try something smarter.

Build a function F(N) which finds out the smallest number with {0, 1, 2} digits which is divisible by N.

So for a given N the number which we are looking for can be written as SUM = 10^n * dn + 10^(n-1) * dn-1 .... 10^1 * d1 + 1*d0 (where di are the digits of the number).

so you have to find out the digits such that SUM % N == 0 basically each digits contributes to the SUM % N with (10^i * di) % N

I am not giving any more hints, but the next hint would be to use DP. Try to figure out how to use DP to find out the digits.

for all numbers between 1 and 10000 it took under 1sec in C++. (in total)

Good luck.

0

精彩评论

暂无评论...
验证码 换一张
取 消