Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- open System.Threading
- open System.Numerics
- let waitFor o= ignore(Monitor.Wait o)
- let wakeWaiters = Monitor.PulseAll
- /// Make a named thread that runs f
- let mkThread name f = Thread (ThreadStart f, Name=name)
- /// Make a named thread and start it immediately
- let startThread name f = (mkThread name f).Start()
- let primes :ref<Set<bigint>>= ref (Set.singleton 2I) //start with just the prime 2, listed //TODO: this is kinda a messy way to say 2
- type bigOddIntGen (min:bigint) =
- let next=ref min
- member this.Next = lock this <| fun () ->
- let v = !next
- next:= v + 2I
- v
- let unchecked = bigOddIntGen(3I)
- ///a lockable object for printign to the screen
- let stdout = ref ()
- let rec primeMaker maxVal :unit=
- let isPrime n =
- ///returns possible prime divisors of the nukmber n (won't return til it has all of them)
- let possibleDivisors = lock primes <| fun () ->
- while (!primes |> Set.maxElement) * (2I) < n do //(Set.exists (fun p -> (bigint 2)*p>=n) (!primes)) do
- printfn "**********************";
- waitFor primes
- Set.filter (fun p -> p<=n/(2I)) (!primes)
- not <| Set.exists (fun p -> n % p = bigint.Zero) possibleDivisors
- let printer name n=
- let pf () = lock stdout <| fun () ->
- ignore <| printfn "%s found prime: %s" name (n.ToString())
- //HACK: BigInt>ToSting is broken: only preserves 50 digits. there is a work around but not using it
- pf ()
- //startThread "printer" pf;
- ///Adds a p to out set of primes
- let addPrime p = lock primes <| fun () ->
- primes:= (!primes).Add p;
- wakeWaiters primes
- let x = unchecked.Next
- if maxVal<>None && x>maxVal.Value then ();
- elif isPrime x then
- printer Thread.CurrentThread.Name x;
- addPrime x;
- primeMaker maxVal;
- //primeMaker "t1" (BigInteger(System.Int32.MaxValue))
- let pm=fun () -> primeMaker <| Some (BigInteger(System.Int32.MaxValue))
- for i in [1..54] do
- let name = sprintf "t%d" i
- startThread name pm;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement