How to generate random number in Free Pascal between 1 and 1,000,000?

I have used a variable type as LongInt, Real, Integer, but there is always an RangeError.

But random number between 1 and 33,333 is working correctly.

Program Random;

var
  a: ...;

begin

a:=random(1000000);

end.

Dani AI

Generated

Short answer: seed the generator once and shift the result up by 1. As already advised, call Randomize at program start to seed the PRNG; to get a value in the inclusive range 1..1,000,000 use Random(1000000) + 1.

A few reasons a RangeError can still appear (these are the common culprits seen in threads like 's):

  • The target variable or a related subrange can't hold the generated value (subrange types or small arrays are a frequent trap).
  • The platform/compiler target uses 16-bit integers (on some targets High(Integer) can be < 1,000,000).
  • The Random call received an invalid argument (zero or negative).
  • Range checking ({$R+}) is enabled and an assignment falls outside the destination range.

Quick checks to diagnose the problem: confirm the platform integer sizes and high values, and ensure the declared variable type can store 1,000,000. A minimal diagnostic approach is to print SizeOf(Integer), High(Integer) and High(LongInt) to see whether the numeric range is sufficient. Also verify there are no accidental subrange declarations like a: 1..33333 or array-index uses that will trigger a range check when a larger number is assigned.

Practical reminders: call Randomize only once at startup (not inside a loop), always pass a positive integer to Random, and add + 1 when you need 1..N instead of 0..N-1. If a RangeError still occurs after those checks, the likely cause is an unexpectedly small declared range (subrange or target type) or an odd compilation target — inspect the variable declaration and the compiler target/mode.

While waiting for more appropriate support, try to load randomize. This seems to work fine for me:

Program Test;

var
  num:longint;

begin
  randomize;
  num:=random(1000000);
  write(num, '');
  writeln;
end.

Source: http://www.freepascal.org/docs-html/rtl/system/randomize.html

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.