[英]Get a non-prime number and its factors below a given maximum
我需要隨機選擇一個低於給定最大值的非素數,並返回其所有因子。
我已經將所有非素數及其因數存儲在Map<Integer, Integer[]>
,該值在啟動時會計算一次。
這是實現的想法:
public Pair<Integer, Integer[]> getNonPrimeAndFactors(int maximum)
{
//Randomly select a non-prime less than maximum
return new Pair<Integer, Integer[]>(nonPrime, factors.get(nonPrime));
}
我不太確定要使用什么數據結構來隨機選擇Map
一個密鑰,但仍然小於maximum
。 選擇一個小於最大值的隨機數,然后迭代調用factors.hasKey(randomNumber--)
可能會有點廢話。
我使用的是Java 7和Guava,因此請選擇Google的收藏集。
通過將鍵集轉換為SortedSet
並使頭部設置保持在最大值以下,可以獲得小於最大值的隨機鍵。
如果有這樣的集合,則可以將其轉換為列表並按索引獲取隨機元素:
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));
}
生成一個低於max的隨機數,通過查看表格來檢查它是否不是素數。 如果是從頭開始的主要重啟,即生成一個新的隨機數。
由於非素數比素數更為頻繁,因此此過程將不會花費很長時間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.