java 使用自定义 IsPrime 方法查找素数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26337833/
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
Finding prime numbers with a custom IsPrime method
提问by Taix
I started learning Java about one month ago and today I saw this question I couldn't solve.
大约一个月前我开始学习 Java,今天我看到了这个我无法解决的问题。
The question was:
问题是:
Write a method named
isPrime
, which takes an integer as an argument and returnstrue
if the argument is a prime number, orfalse
otherwise. Demonstrate the method in a complete program.
编写一个名为 的方法
isPrime
,它接受一个整数作为参数,true
如果参数是素数则返回,false
否则返回。在完整的程序中演示该方法。
And the second part says:
第二部分说:
Use the
isPrime
method that you wrote in previous program in a program that stores a list of all the prime numbers from1
through100
in a file.
使用
isPrime
方法是在你前面的程序在程序中写道,存储从所有质数的列表,1
通过100
在一个文件中。
Here's my code, which doesn't work:
这是我的代码,它不起作用:
import java.io.*;
public class PrimeNumbers {
public static void main (String args[]) throws IOException {
PrintWriter outputFile = new PrintWriter("PrimeNumber.txt");
int j = 0;
for (int i = 0; i < 100; i++) {
isPrime(i);
outputFile.println("Prime nums are:" + i);
}
}
public static boolean isPrime (int j) {
int i;
for (j = 2; j < i; j++) {
if (i % j == 0) {
return false;
}
if (i == j) {
return true;
}
}
}
}
回答by Eran
Your condition for returning true
in isPrime
- if (i == j)
- can never be met, since it's inside a loop whose condition is j < i
. Instead, just return true
after the loop. If the loop ends without returning false
, you know for sure that the input number is prime.
您的返回状态true
中isPrime
- if (i == j)
-永远不能满足,因为它是一个循环,其条件是内部的j < i
。相反,只需true
在循环后返回即可。如果循环结束而不返回false
,则您肯定知道输入数字是素数。
Your code that uses isPrime
is not checking the value returned by this method. You must check it in order to decide whether to write the number to the output file.
您使用的代码isPrime
不检查此方法返回的值。您必须检查它以决定是否将数字写入输出文件。
回答by BullyWiiPlaza
import java.io.IOException;
import java.io.PrintWriter;
public class PrimeNumbers
{
public static void main(String args[]) throws IOException
{
PrintWriter primeNumbersWriter = new PrintWriter("PrimeNumber.txt");
for (int i = 0; i < 100; i++)
{
// You didn't do anything with the return value of isPrime()
if (isPrime(i))
{
primeNumbersWriter.println("Prime numbers are: " + i);
}
}
// Please close writers after using them
primeNumbersWriter.close();
}
public static boolean isPrime(int prime)
{
// Do not use the number to check for prime as loop variable, also it's
// sufficient to iterate till the square root of the number to check
for (int number = 2; number < Math.sqrt(prime); number++)
{
if (prime % number == 0)
{
return false;
}
}
// You didn't always return a value, it won't let you compile otherwise
return true;
}
}
回答by CoderCroc
Prime Number
A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.
Prime Number
质数(或质数)是大于 1 的自然数,除了 1 和它本身之外没有其他正除数。
What should be the logic?
应该是什么逻辑?
- Pass a number to method.
- Use loop to start a check of modulo
%
to find at leastone number which can divide the passed number. - Check until we reached the value
passedNumber
. - If the modulo gives
0
for atleast one, it's not prime thank god! - If modulo is not
0
for any number ...oh man it'sPrime.
- 将数字传递给方法。
- 使用循环开始检查模数
%
以找到至少一个可以整除传递数字的数字。 - 检查直到我们达到值
passedNumber
。 - 如果模数给出
0
至少一个,那就不是素数了,谢天谢地! - 如果模不是
0
任何数字......哦,伙计,它是Prime.
What are the problems in your code?
你的代码有什么问题?
- You are looping correctly but using the variable
j
which is the limit and you are incrementing it! - If you want to loop through
i < j
how can the conditioni == j
be true? - If method is returning
boolean
why are you using method asvoid
! Use that returned value. - You can just return false at the end if divisor not found!
- 您正在正确循环,但使用的变量
j
是限制并且您正在增加它! - 如果要循环
i < j
,条件如何i == j
为真? - 如果方法正在返回
boolean
为什么你使用方法作为void
!使用该返回值。 - 如果找不到除数,您可以在最后返回 false!
We did it...Just try now!
我们做到了……现在就试试吧!
回答by CIsForCookies
about isPrime: First of all, u should loop for( j = 2; j*j <= i; j++)
关于 isPrime:首先,你应该循环 for( j = 2; j*j <= i; j++)
the reason for this loop is that if a number isn't prime, its factor must be less or equal to the squared root of i, so there is no need to loop after that pointnow, if loop didn't return false - return true`
这个循环的原因是,如果一个数不是素数,它的因数必须小于或等于 i 的平方根,所以现在不需要在那个点之后循环,如果循环没有返回假 - 返回真的`
about second function: use if before checking isPrime - if(isPrime(i)) {add i to list}
关于第二个功能:在检查 isPrime 之前使用 if - if(isPrime(i)) {add i to list}
回答by T.Malik
see here is your solution.
看到这里是你的解决方案。
import java.util.Scanner;
public class Testing {
public static void main(String args[]) {
Scanner scnr = new Scanner(System.in);
int number = Integer.MAX_VALUE;
System.out.println("Enter number to check if prime or not ");
while (number != 0) {
number = scnr.nextInt();
System.out.printf("Does %d is prime? %s %s %s %n", number,
isPrime(number), isPrimeOrNot(number), isPrimeNumber(number));
}
}
/*
* Java method to check if an integer number is prime or not.
* @return true if number is prime, else false
*/
public static boolean isPrime(int number) {
int sqrt = (int) Math.sqrt(number) + 1;
for (int i = 2; i < sqrt; i++) {
if (number % i == 0) {
// number is perfectly divisible - no prime
return false;
}
}
return true;
}
/*
* Second version of isPrimeNumber method, with improvement like not
* checking for division by even number, if its not divisible by 2.
*/
public static boolean isPrimeNumber(int number) {
if (number == 2 || number == 3) {
return true;
}
if (number % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(number) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (number % i == 0) {
return false;
}
}
return true;
}
/*
* Third way to check if a number is prime or not.
*/
public static String isPrimeOrNot(int num) {
if (num < 0) {
return "not valid";
}
if (num == 0 || num == 1) {
return "not prime";
}
if (num == 2 || num == 3) {
return "prime number";
}
if ((num * num - 1) % 24 == 0) {
return "prime";
} else {
return "not prime";
}
}
}