纯随机数发生器
import java.util.ArrayList;
import java.util.List;
public class LinearCongruentialGenerator {
private long seed;
private long modulus;
private long multiplier;
private long increment;
public LinearCongruentialGenerator(long seed, long modulus, long multiplier, long increment) {
this.seed = seed;
this.modulus = modulus;
this.multiplier = multiplier;
this.increment = increment;
}
public long next() {
seed = (multiplier * seed + increment) % modulus;
return seed;
}
public static List<Long> generateRandomIntegers(int count) {
long modulus = Integer.MAX_VALUE;
long multiplier = 16807;
long increment = 0;
long seed = System.currentTimeMillis() % modulus; // 使用当前时间的毫秒数作为种子
LinearCongruentialGenerator generator = new LinearCongruentialGenerator(seed, modulus, multiplier, increment);
List<Long> randomIntegers = new ArrayList<>();
for (int i = 0; i < count; i++) {
randomIntegers.add(generator.next());
}
return randomIntegers;
}
public static void main(String[] args) {
int count = 1000;
List<Long> randomIntegers = generateRandomIntegers(count);
for (long randomInteger : randomIntegers) {
System.out.println(randomInteger);
}
}
}
程序定义了两个名为square
的方法,一个接受整数参数,另一个接受双精度浮点数参数。这两个方法具有相同的名称,但它们的参数类型不同。重载的square
方法接受不同类型的参数,因此它们可以返回不同类型的结果。一个方法返回整数,另一个返回双精度浮点数。