//----------------------------------------------------------------------
//  IMPLEMENTATION FILE (rand2.cpp)
//  This module exports a class for pseudorandom number generation
//  Machine dependency: long ints must be at least 32 bits (4 bytes).
//----------------------------------------------------------------------
#include "rand2.h"

const long MULTIPLIER = 16807;
const long MAX =  2147483647;
const long QUOT = 127773;       // Quotient of MAX / MULTIPLIER
const long REM  = 2836;         // Remainder of MAX / MULTIPLIER

// Private members of class:
//     long currentSeed
//
// CLASSINV: 1 <= currentSeed < MAX

RandGen::RandGen( /* in */ long initSeed )
    //..................................................................
    // Constructor
    // PRE:  initSeed >= 1
    // POST: 1 <= currentSeed < MAX
    //..................................................................
{
    initSeed = initSeed % MAX;
    currentSeed = (initSeed > 0) ? initSeed : 1;
}

RandGen::RandGen()
    //..................................................................
    // Default constructor
    // POST: currentSeed == 4
    //..................................................................
{
    currentSeed = 4;
}

float RandGen::NextRand()
    //..................................................................
    // POST: currentSeed == (currentSeed * MULTIPLIER) modulo MAX
    //    && FCTVAL == currentSeed / MAX
    // NOTE: This is a prime modulus multiplicative linear congruential
    //       generator
    //..................................................................
{
    long temp = MULTIPLIER*(currentSeed%QUOT) - REM*(currentSeed/QUOT);

    currentSeed = (temp > 0) ? temp : temp + MAX;
    return float(currentSeed) / float(MAX);
}