I was asked a question one day: find an integer n such that the first five digits of 5*7^n is 12345. It's very nice that I can quickly write code like this:
Block[{n=1,x=5},
While[RealDigits[x=7.*x][[1,;;5]]!={1,2,3,4,5},n++];
n]//Timing
{55.86399999999998,456370}
It takes less than a minute.
Later, I found that using the function FindInstance I could find a solution in much less time (but not the minimal solution):
FindInstance[{m+Log[10,1.2345]<Log[10,5.]+n Log[10,7.]<m+Log[10,1.2346],n>0},{m,n},Integers]//Timing
{0.3119999999999869,{{m->12872681,n->15232174}}}
Furthermore, I modified the code to be able to find the minimal solution like this:
NestWhileList[
n/.FindInstance[{m+Log[10,1.2345]<Log[10,5.]+n Log[10,7.]<m+Log[10,1.2346],First@#>n>0},{m,n},Integers]&,
n/.FindInstance[{m+Log[10,1.2345]<Log[10,5.]+n Log[10,7.]<m+Log[10,1.2346],n>0},{m,n},Integers],
#!={}&]//Timing
{11.872000000000007,{{15232174},{15188314},{10277666},{5410878},{2955299},{499720},
{497170},{496660},{496150},{494620},{493090},{492580},{492070},{490540},{490030},{489520},{489010},{478300},{456370},n}}
The time it takes is one fifth of that classic method. So, I found a new way to solve this class of questions (just in Mathematica)?
My question is, can this method be used for other questions, and which mathematical method does the function FindInstance exactly use?
FindInstanceuse unknown proprietary algorithm. Perhaps it is slower because it find pair of tho integers (n,m) instead of one integer. – ybeltukov Sep 27 '13 at 15:50