'BlumBlumShub Randomizer
uses console

================
class BlumPrimes
================
'
int nn 'array elements
sys p 'array buffer address
'
method constructor(int n)
=========================
'generate primes
int i,j,k,t
t=n*2
redim quad q(t+1)
quad r
quad m=1
indexbase 0
nn=n
i=0
while i<t
  k=1
  for j=2 to i-1
    r=mod(m,q[j])
    if r=0
      k=0
      exit for
    endif
  next
  if k
    i++
    q[i]=m
  endif
  m++
wend
'filter for Blum primes
j=0
for i=1 to t
  k=q[i] 'clipped to 32bits
  if (k and 3) = 3 'quick modulo 4
    j++
    q[j]=q[i]
    if j>=nn
      exit for
    endif
  endif
next
nn=j
print i cr
p=@q
end method
'
method get(int i) as quad
if i<1 or i>nn
  exit method
endif
quad q at (i*8+p)
return q
end method
'
end class 'BlumPrimes
'
'TEST
'new BlumPrimes BP(1000)
'int i
'for i=1 to BP.nn
'  print i tab BP.get(i) cr
'next
'del BP
'wait


==================
class BlumBlumShub
==================
'
quad P,Q,N,state
'
method constructor(dword iP, iQ, iseed)
  'P(P), Q(Q), N(P * Q), state(seed) {}
  P=iP
  Q=iQ
  N=iP*iQ
  state=iseed
end method

method get() as quad
  'state = mod(state * state,N)
  state = (state * state) mod N
  return state
end method

method getBit() as int
  return mod(get(), 2)
end method

end class 'BlumBlumShub

  'TEST
  =====
  ' Choose large Blum prime numbers P and Q
  ' Blum prime numbers (where P ≡ 3 (mod 4))
  quad P = 17159 '11
  quad Q = 17167 '23
  quad seed = 1234
  new BlumBlumShub brnd(P, Q, seed)
  '
  ' Generate a sequence of random numbers
  int i
  for i=0 to 19
    print i tab " " brnd.get() cr
  next
  '
  wait
  del brnd
