[英]Get a non-prime number and its factors below a given maximum
I need to randomly pick a non-prime number below a given maximum, and return all its factors. 我需要随机选择一个低于给定最大值的非素数,并返回其所有因子。
I already have all the non-primes and their factors stored in a Map<Integer, Integer[]>
that is calculated once on startup. 我已经将所有非素数及其因数存储在
Map<Integer, Integer[]>
,该值在启动时会计算一次。
Here's an idea of the implementation: 这是实现的想法:
public Pair<Integer, Integer[]> getNonPrimeAndFactors(int maximum)
{
//Randomly select a non-prime less than maximum
return new Pair<Integer, Integer[]>(nonPrime, factors.get(nonPrime));
}
I'm not really sure what data structure to use in order to pick a key in that Map
randomly whilst still being less than maximum
. 我不太确定要使用什么数据结构来随机选择
Map
一个密钥,但仍然小于maximum
。 Picking a random number less than maximum, then iterating down calling factors.hasKey(randomNumber--)
would be a bit crap. 选择一个小于最大值的随机数,然后迭代调用
factors.hasKey(randomNumber--)
可能会有点废话。
I'm using Java 7 and Guava, so have Google's collections to pick from. 我使用的是Java 7和Guava,因此请选择Google的收藏集。
You can get a random key less than the maximum by converting the key set to a SortedSet
and keep the head set below the maximum value. 通过将键集转换为
SortedSet
并使头部设置保持在最大值以下,可以获得小于最大值的随机键。
When you have such a set, it is then possible to convert it to a list and get a random element by index: 如果有这样的集合,则可以将其转换为列表并按索引获取随机元素:
public Pair<Integer, Integer[]> getNonPrimeAndFactors(int maximum) {
SortedSet<Integer> set = new TreeSet<>(factors.keySet()).headSet(maximum);
List<Integer> keys = new ArrayList<>(set);
Integer nonPrime = keys.get(ThreadLocalRandom.current().nextInt(keys.size()));
return new Pair<Integer, Integer[]>(nonPrime, factors.get(nonPrime));
}
generate a random number below max, check if it is a non-prime by looking into the table. 生成一个低于max的随机数,通过查看表格来检查它是否不是素数。 If it is a prime restart from the beginning, ie generate a new random number.
如果是从头开始的主要重启,即生成一个新的随机数。
Since the non-primes are much more frequent than the primes this procedure will not take long. 由于非素数比素数更为频繁,因此此过程将不会花费很长时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.