MathGroup Archive 2008

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

Search the Archive

Re: Nested If


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


  • Prev by Date: Re: Nested If
  • Next by Date: Re: Solve vs. NSolve
  • Previous by thread: Nested If
  • Next by thread: Re: Re: Nested If