简体   繁体   English

在java中使用while循环查找素数

[英]find prime number using while loop in java

I wanna find prime numbers.我想找到质数。 It divides n by all numbers between 2 and (n–1) , but it is wrong somewhere.它将n除以2(n–1)之间的所有数字,但在某处是错误的。 For example 9 , it gives true .例如9 ,它给出true

Appreciate any help.感谢任何帮助。

public void isPrime(int n) {

    int i = 2;
    while (i <= (n - 1)) {
        if (n % i == 0) {
            System.out.println("It's not a prime number");
            break;
        } else {
            System.out.println("It's a prime number");
            break;
        }
        i++;
    }
}

The statement i++ is unreachable, so you don't want the else{...} to contain break .语句i++无法访问,因此您不希望else{...}包含break Instead, you simply want else i++ .相反,您只需要else i++

Where you want the "is prime" statement is outside the loop, since you don't know n is prime until the loop finishes checking all the divisors.您想要“是素数”语句的位置在循环之外,因为在循环完成检查所有除数之前您不知道n是素数。

And you don't want break inside the if ;而且您不想在ifbreak you want return , because otherwise it'll print "is prime".你想要return ,否则它会打印“是素数”。

PS You can make the while say while(i < Math.sqrt(n)) to reduce iterations (think about it). PS你可以让while说while(i < Math.sqrt(n))来减少迭代(想想看)。

EDIT编辑

You might want to make the return type boolean instead of printing messages, putting return false if there's a divisor and return true if there was no divisor.您可能希望将返回类型设为boolean而不是打印消息,如果有除数则return false如果没有除数则return true

this method will return a boolean if your number is prime or not.如果您的数字是素数,此方法将返回一个布尔值。 In the for loop you can see that we first test 2. If our number isn't divisible by two then we don't have to test any even numbers.在 for 循环中,您可以看到我们首先测试 2。如果我们的数字不能被 2 整除,那么我们不必测试任何偶数。 This is a very efficient way to test for prime numbers.这是测试质数的一种非常有效的方法。

   boolean isPrime(int n) {
    for(int i=2;2*i<n;i++) {
        if(n%i==0)
            return false;
    }
    return true;
}

Here's the code for prime number,这是素数的代码,

import java.util.Scanner;

public class JavaPrimeNumber 
{
   public static void main(String[] args) 
   { 
      boolean checkPrime = true;
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter any number find prime number in java : "); 
      int number = sc.nextInt();

      int a = 2;
      while(a <= number / 2)
      {
         if(number % a == 0)
         {
            checkPrime = false;
            break;
         }
         a++;
      }

      if(checkPrime)
         System.out.println(number + " is a prime number.");
      else
         System.out.println(number + " is not a prime number.");
      sc.close();
   }
}

The problem is that you break out of the loop on the first check: you divide by 2 and report the answer based only on that.问题是您在第一次检查时跳出了循环:您除以 2 并仅根据该结果报告答案。

Restructure your loop so that the decision "It's a prime number" is delayed until you get all the way through the loop.重组您的循环,以便“这是一个质数”的决定被延迟,直到您完全通过循环。 You may want to set a boolean variable for this.您可能想为此设置一个布尔变量。

Also, I recommend using a for loop, since you know the maximum number of times you'll iterate.另外,我建议使用 for 循环,因为您知道迭代的最大次数。 Note that you don't have to go to n-1, just to sqrt(n).请注意,您不必转到 n-1,只需转到 sqrt(n)。

public void isPrime(int n) {
    if(n % 2 == 0) {
       System.out.println("It is not a prime number");
       return;
    }   
    else {
       int i = 3;
       while(i <= Math.sqrt(n) ) {
           if( (n % i) == 0) {
              System.out.println("It is not a prime number");
              return;
           }
           i = i + 2; 
       }
    }
    System.out.println("It is a prime number");
    return;

}

You can do the while loop in this way, first you want to check if no is divisible by 2, if so it is not a prime number.您可以通过这种方式执行 while 循环,首先您要检查 no 是否可以被 2 整除,如果是,则它不是素数。 If not check for odd nos till square root of n.如果不检查奇数直到 n 的平方根。 Dont need to check for even, if no is not divisible by 2 it will not be divisible by any even number.不需要检查偶数,如果 no 不能被 2 整除,它就不能被任何偶数整除。

//import java.util.*;
import java.util.Scanner;
class Primenos
{   public static void main(String args[])
    {   int no, flag = 0, a, b;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter any no: ");
        no = sc.nextInt();
        a=1;
        while(a<=no)
        {
            flag=0;
            b=2;
            while(b<=a>>1)
            {
                if(a%b==0)
                {   flag = 1;
                    break;
                }
                b++;
            }
            if(flag==0)
            {   System.out.println("Prime number" + a);
            }
            else
            {   System.out.println("Not Prime number" + a);
            }
            a++;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM