Mathematica 9 is now available
Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2001

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

Search the Archive

Re: Can this be made cleaner and more efficient?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg29076] Re: Can this be made cleaner and more efficient?
  • From: "Allan Hayes" <hay at haystack.demon.co.uk>
  • Date: Sun, 27 May 2001 18:04:43 -0400 (EDT)
  • References: <9eksm9$7r9@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

Here are a two attempts:


MakeRandomOdd[p_] :=
  With[{tst = Or @@ (#1 == 0 & ) /@ NestWhileList[
        Mod[#1[[1]], NextPrime[#1[[2]]]] & , Mod[#1, 2],
        #1[[2]] < p & , 1, Infinity, -1]},
   RandomOdd[d_] := NestWhile[
     Random[Integer, {10^(d - 1), 10^d}] & , 0, tst & ]]

MakeRandomOdd[100];
SeedRandom[1]
Timing[ans1 = RandomOdd2 /@ Range[1, 500]; ]

{2.19 Second, Null}


MakeRandomOddFn[p_] :=
  With[{tst = Or @@ (#1 == 0 & ) /@ NestWhileList[
        Mod[#1[[1]], NextPrime[#1[[2]]]] & , Mod[#1, 2],
        #1[[2]] <= p & , 1, Infinity, -1]},
   With[{d = #1}, NestWhile[Random[Integer,
        {10^(d - 1), 10^d}] & , 0, tst & ]] & ]

fn = MakeRandomOddFn[100];
SeedRandom[1]
Timing[ans2 = fn /@ Range[1, 500]; ]

{2.14 Second,Null}

ans1 === ans2

True
--
Allan
---------------------
Allan Hayes
Mathematica Training and Consulting
Leicester UK
www.haystack.demon.co.uk
hay at haystack.demon.co.uk
Voice: +44 (0)116 271 4198
Fax: +44 (0)870 164 0565

"Flip" <nospam at newsranger.com> wrote in message
news:9eksm9$7r9 at smc.vnet.net...
> Hi All,
>
> I was wondering if the following module (it is small) can be made simpler
and
> faster ... and thoughts would be appreciated.
>
> RandomOdd2[d_] := Module[{res},
> res = Random[Integer, {10^(d - 1), 10^d}];
> While[(
>
> Mod[res, 02] == 0 || Mod[res, 03] == 0 || Mod[res, 05] == 0 ||
> Mod[res, 07] == 0 || Mod[res, 11] == 0 || Mod[res, 13] == 0 ||
> Mod[res, 17] == 0 || Mod[res, 19] == 0 || Mod[res, 23] == 0 ||
> Mod[res, 29] == 0 || Mod[res, 31] == 0 || Mod[res, 37] == 0 ||
> Mod[res, 41] == 0 || Mod[res, 43] == 0 || Mod[res, 47] == 0 ||
> Mod[res, 53] == 0 || Mod[res, 59] == 0 || Mod[res, 61] == 0 ||
> Mod[res, 71] == 0 || Mod[res, 73] == 0 || Mod[res, 79] == 0 ||
> Mod[res, 83] == 0 || Mod[res, 89] == 0 || Mod[res, 97] == 0),
> res = Random[Integer, {10^(d - 1), 10^d}]];
> res]
>
> It is basically sieving out the first 24 primes (primes <= 100) from the
result.
>
> Thank you ... Flip
>
>




  • Prev by Date: Re: Converting from string to integer and back
  • Next by Date: RE: Re: ColorFunction for ListPlot3D, ListContourPlot or ListDensityPlot ?
  • Previous by thread: Re: Can this be made cleaner and more efficient?
  • Next by thread: RE: Re: Can this be made cleaner and more efficient?