MathGroup Archive 2008

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Re: Nested If


Daniel Lichtblau wrote:
> Artur wrote:
>> Dear Mathematica Gurus,
>> Who know how nested or folded multiple If procedure in following:
>>
>> {m1, m2, m3, m4, m5, m6, m7, m8,  m9} = {-1, -1, -1, -1, -1, -1, -1, -1, 
>> -1}; Do[
>>  If[Mod[n, 2] == 0, m1 = m1 + 1,
>>   If[Mod[n, 3] == 0, m2 = m2 + 1,
>>    If[Mod[n, 5] == 0, m3 = m3 + 1,
>>     If[Mod[n, 7] == 0, m4 = m4 + 1,
>>      If[Mod[n, 11] == 0, m5 = m5 + 1,
>>       If[Mod[n, 13] == 0, m6 = m6 + 1,
>>        If[Mod[n, 17] == 0, m7 = m7 + 1,
>>         If[Mod[n, 19] == 0, m8 = m8 + 1,
>>          If[Mod[n, 23] == 0, m9 = m9 + 1]]]]]]]]], {n, 1,   6!}];
>> Print[{m1, m2, m3, m4, m5, m6, m7, m8, m9}]
>>
>> I want nested 9 times If[Mod[n,Prime[k]]==0,m[k]=m[k]+1],{k,1,9}]
>>
>> I will be greatfull for any idea!
>>
>> Best wishes
>> Artur
>>
> 
> len = 9;
> mlist = ConstantArray[-1,len]
> 
> Could do this procedurally with a nested loop.
> 
> Do [Do [If [Mod[n,Prime[k]]==0, mlist[[k]]=mlist[[k]]+1;Break[]],
>    {k,len}], {n,6!}]
> 
> Or use NestWhile to keep looking for a prime divisor,
> 
> Do[NestWhile[#+1&,1,(Mod[n,Prime[#]]!=0||(mlist[[#]]=mlist[[#]]+1;False))&,
>   1,len], {n,6!}]
> 
> Me, I'd do it the first way.
> 
> Daniel Lichtblau
> Wolfram Research

Somewhat faster:

countFirstDivisors = Compile[{{max,_Integer},{ndivs,_Integer}},
   Module[{mlist=ConstantArray[-1,ndivs],primes=Prime[Range[ndivs]]},
   Do [Do [If [Mod[n,primes[[k]]]==0,mlist[[k]]++;Break[]],
     {k,ndivs}], {n,max}];
   mlist
   ]]

Example:

In[51]:= Timing[countFirstDivisors[10!,9]]

Out[51]= {2.18167, {1814399, 604799, 241919, 138239, 75402,
   58003, 40941, 34478, 26982}}

Much faster is to work out the right formula for these counts. Lucky me, 
I did that in a MathGroup thread around a decade ago.

frac[k_] := Product[(Prime[j]-1)/Prime[j],{j,k-1}]/Prime[k]

countFirstDivisors2[max_,ndivs_] :=
   Table[-1+Floor[max*frac[k]], {k,ndivs}]

In[55]:= Timing[countFirstDivisors2[10!,9]] // InputForm

Out[55]//InputForm=
{8.895661984809067*^-15, {1814399, 604799, 241919, 138239,
   75402, 58001, 40942, 34477, 26982}}

Daniel Lichtblau
Wolfram Research


  • Prev by Date: Re: time based moving average (and other newbie mathematica
  • Next by Date: Re: integration
  • Previous by thread: Re: Nested If
  • Next by thread: Re: Re: Re: Nested If