有誰知道可用於提供特定長度(k)的所有素數的基於Java的庫。例如,如果k = 2,庫將提供:11,13,17 .. 87.基於Java的庫提供特定長度的素數
3
A
回答
2
1
我也不知道圖書館。但是這裏有一些我寫的代碼可以做到這一點。我認爲這對其他需要太漂亮了可重複使用:
package com.sandbox;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
public class SandboxTest {
@Test
public void whenGettingNextThenItIsNextPrime() {
Primes primes = new Primes();
assertEquals((Long) 2L, primes.next());
assertEquals((Long) 3L, primes.next());
assertEquals((Long) 5L, primes.next());
assertEquals((Long) 7L, primes.next());
assertEquals((Long) 11L, primes.next());
}
@Test
public void whenPassingIn2ThenIsPrime() {
assertTrue(new Primes().isPrime(2));
}
@Test
public void getAllPrimesOfLength2() { //this does what your question asks
Primes primes = new Primes();
while (true) {
Long prime = primes.next();
int length = String.valueOf(prime).length();
if (length > 2) {
return; //we found them all
} else if (length == 2) {
System.out.println(prime);
}
}
}
}
而這裏的實現:
package com.sandbox;
import java.util.Iterator;
public class Primes implements Iterator<Long>{
private long currentPrime = 1;
public boolean hasNext() {
return true;
}
public Long next() {
currentPrime++;
while (!isPrime(currentPrime)) {
currentPrime++;
}
return currentPrime;
}
/**
* Optimize this on your own
*/
public boolean isPrime(long numberInQuestion) {
for (int i = 2; i < numberInQuestion - 1; i++) {
if (numberInQuestion % i == 0) {
return false;
}
}
return true;
}
public void remove() {
throw new UnsupportedOperationException();
}
}
相關問題
- 1. 如何基於特定長度的文本求和
- 2. 什麼特定的Spark庫「提供」?
- 3. 如果數據長度大於特定長度,jquery datatable
- 4. PHP基於特定元素
- 5. NUnit的 - 基於XML數據提供
- 6. 基於文件的數據提供者
- 7. 獲取長度提供
- 8. 從Java中提取維基百科表中的特定元素
- 9. 的jQuery基於元素長度元素添加ID
- 10. 基於更長的流創建具有固定長度的流
- 11. 乘dataframes提供關於列名目前存在的長度
- 12. 具有特定長度的React.PropTypes數組
- 13. 基於URL長度的API的性能
- 14. 基於「條款」的長度的性能
- 15. 基於Python中的標題提取特定列中的數據
- 16. VB6 - 基於標題長度
- 17. cbind不同長度基於
- 18. 基於長度讀取行
- 19. String.Split - 省略空數組元素或低於一定的長度
- 20. 排序基於參數陣列長度
- 21. 從基於關鍵字的固定長度的文本中提取字符串
- 22. 以表單形式提供基於php的元素
- 23. 基於其相應的XML元素提取Java元素
- 24. 基於陣列長度的html列表元素
- 25. PHP:提供特定於「媒體查詢報告的屏幕寬度」的內容
- 26. 從基於參數的mysql數據庫檢索特定值
- 27. 基於範圍的霧使用長度(vec4)還是長度(vec3)?
- 28. 基於字節而非長度的字符串長度驗證
- 29. ORACLE - 基於查詢設置varchar2長度的長度
- 30. 的Javascript:基於正文長度
時間超過2位,指定所有你列出的電話號碼。 – 2013-03-26 00:42:38
@Hunter,不知道你的意思。你能澄清嗎? – 2013-03-26 00:47:08
基數爲10的數字11是二進制的「1011」。它需要4位來顯示它的二進制表示 – 2013-03-26 00:49:02