Java素数法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26247466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Prime Number Method
提问by VMoza
The question is exactly as follows:
问题如下:
Write a method that determines whether a number is prime. Then use this method to write an application that determines and displays all the prime numbers less than 10,000.
编写一个方法来确定一个数是否为素数。然后使用此方法编写一个应用程序,确定并显示所有小于 10,000 的质数。
I have already written a program that finds all prime numbers up to 10,000, but then found a simpler and more efficient one on StackOverflow, and that is this:
我已经编写了一个程序,可以找到最多 10,000 的所有质数,但后来在 StackOverflow 上找到了一个更简单、更高效的程序,那就是:
package prime;
import java.util.Scanner;
public class Prime
{
public static void main(String[] args)
{
for(int i = 1; i <= 10000; i++)
{
int factors = 0;
int j = 1;
while(j <= i)
{
if(i % j == 0)
{
factors++;
}
j++;
}
if (factors == 2)
{
System.out.println(i);
}
}
}
}
Since I am very new to Java and am especially not good at methods, this problem is especially difficult for me. I tried making a method, but nothing is being returned, and when I try to return something I get error after error after error.
由于我对Java很陌生,特别不擅长方法,所以这个问题对我来说特别困难。我尝试创建一个方法,但没有返回任何内容,当我尝试返回某些内容时,我在一个接一个的错误中出错。
The help I need is mainly just Pseudo-Code for what I should do to tackle this problem; I'm not asking you for the answer, I'm just asking for a start.
我需要的帮助主要只是伪代码,我应该怎么做才能解决这个问题;我不是在问你答案,我只是在问一个开始。
采纳答案by Subin Sebastian
package prime;
public class Prime
{
public static void main(String[] args)
{
for(int i = 1; i <= 10000; i++)
{
if (isPrimeNumber(i))
{
System.out.println(i);
}
}
}
public static boolean isPrimeNumber(int i) {
int factors = 0;
int j = 1;
while(j <= i)
{
if(i % j == 0)
{
factors++;
}
j++;
}
return (factors == 2);
}
}
回答by dramzy
Write a method that determines whether a number is prime. Then use this method to write an application that determines and displays all the prime numbers less than 10,000.
编写一个方法来确定一个数是否为素数。然后使用此方法编写一个应用程序,确定并显示所有小于 10,000 的质数。
It seems to me that you need a method that returns true if the number you pass it is prime and false otherwise. So, all you really need to do here is to move the portion of the code that deals with determining if a number is prime and, inside that method, instead of printing the number when it is prime, return true, otherwise return false. Then, inside the main method, print the number if that function indicates that the current integer is prime (by returning true) or do nothing otherwise. This is the best I can do to explain the solution without giving you the actual code.
在我看来,您需要一种方法,如果您传递的数字是素数,则返回 true,否则返回 false。因此,您真正需要在这里做的就是移动处理确定数字是否为质数的代码部分,并且在该方法中,当数字为质数时不打印数字,而是返回真,否则返回假。然后,在 main 方法中,如果该函数指示当前整数是素数(通过返回 true),则打印数字,否则不执行任何操作。这是我在不给您实际代码的情况下解释解决方案所能做的最好的事情。
EDIT:Since you asked for pseudocode:
编辑:因为你要求伪代码:
main()
for i in 1..10000 :
if isPrime(i)
print i
isPrime(i):
factors = 0
num = 1
while num is less than or equal to i:
if i mod nums is 0:
increment factors
increment nums
return (factors == 2)
回答by Friat
static int primeNumber(int n){
int i = 1, factor = 0;
while(i <= n){
if(n % i == 0){
factor++;
}
i++;
}
if (factor == 2){
return 1;
}
return 0;
}
回答by Miracle Ma
/**
* List all prime numbers from 101 to 200
* for responding your question, I think it is a good view to have it done
* @ Joannama
*
*/
public class PrimeNum
{
public static void main(String[] args)
{
for ( int i = 101; i <= 200 ; i += 2)
{
// get rid of even number from 101 to 200
//because even number are never a prime number
boolean f = true;
//assume these numbers are prime numbers
for ( int j = 2; j < i; j++)
{
if ( i % j == 0)
{
f = false;
// if the reminder = 0,
//which means number is not a prime,
//therefore f = false and break it
break;
}
}
if ( ! f)
{
continue;
}
System.out.print("\u0020" + i);
}
}
}
回答by Brenann
public boolean isPrime(long num)
{
double limit = Math.sqrt(num);
for (long i = 2; i < limit; i++)
if(num%i == 0)
return false;
return true;
}
回答by oleg.cherednik
I have found one more solution using java streams:
我找到了另一种使用 java 流的解决方案:
import java.util.stream.LongStream;
public static boolean isPrime(long num) {
return num > 1 && LongStream.rangeClosed(2, (long)Math.sqrt(num)).noneMatch(div-> num % div== 0);
}
Here goes a test case to prove this works:
这里有一个测试用例来证明这是有效的:
// First 168 primes, retrieved from https://en.wikipedia.org/wiki/Prime_number
private static final List<Integer> FIRST_168_PRIMES =
Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997);
@Test
public void testNumberIsPrime() {
FIRST_168_PRIMES.stream().forEach(integer -> assertTrue(isPrime(integer)));
}
@Test
public void testNumberIsNotPrime() {
List<Integer> nonPrime = new ArrayList<>();
for (int i = 2; i < 1000; i++) {
if (!FIRST_168_PRIMES.contains(i)) {
nonPrime.add(i);
}
}
nonPrime.stream().forEach(integer -> assertFalse(isPrime(integer)));
}
回答by Dragoslav Petrovic
As the Brenann posted. Best way to calculate if its a prime, but with only one correction to the limit. You must add 1 to it, or it detects false positives.
正如布伦南发布的那样。计算它是否是素数的最佳方法,但只对极限进行一次修正。您必须向其添加 1,否则它会检测到误报。
public boolean isPrime(long num){
double limit = Math.sqrt(num) + 1;
for (long i = 2; i < limit; i++)
if(num%i == 0)
return false;
return true;
}
just be sure to start with 3
一定要从 3 开始
回答by Hani
Dragoslav Petrovic solution is ok, but it returns bad result when passing 2 as input, which is also a prime number. This is how I resolved it:
Dragoslav Petrovic 解决方案是可以的,但是当将 2 作为输入(它也是一个质数)时,它会返回错误的结果。我是这样解决的:
public boolean isPrime(int number) {
if (number <= 1) {
System.out.println("Only positive numbers above 1 can be prime.");
return false;
}
double limit = Math.sqrt(number);
for (int i = 2; i <= limit; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}