简体   繁体   English

找出第 n 个质数

[英]Find the nth prime number

I don't know why my code won't work when I input certain nthprime numbers.我不知道为什么当我输入某些 nthprime 数字时我的代码不起作用。 I have tried to alter my code a couple of times but for every one nthprime I make it work, I make it worse for others.我曾多次尝试更改我的代码,但是对于每一个我让它工作的第 nthprime,我都会让其他人变得更糟。 So if I change my code to make it work for nthprime=8, I realize nthprime=7 and some others stop working.因此,如果我更改我的代码以使其适用于 nthprime=8,我会意识到 nthprime=7 而其他一些则停止工作。 Can anyone point out a specific flaw I made or maybe I should rethink the outline of my code.谁能指出我犯的一个具体缺陷,或者我应该重新考虑我的代码大纲。 Thank you.谢谢你。

public class NthPrime {

public static void main(String[] args) {

    int nthprime;

    System.out.println("Enter value for n:");
    nthprime=IO.readInt();

    while(nthprime <= 0){
        System.out.println("Enter a positive value for n");
        nthprime=IO.readInt();
    }

    if(nthprime == 1){
        System.out.println("The nth prime number is: "+2);
    }
    if(nthprime == 2){
        System.out.println("The nth prime number is: "+3);
    }

    if(nthprime > 2){

    int prime=2; 
    int num=3;
    int square;
    boolean nonprime=false;

    while(prime < nthprime){
        prime++;
        num+=2;
        square = (int) Math.sqrt(num);
        for (int i=3; i <= square; i++){
            if (num % i == 0){
                nonprime=true;
                num+=2;
            }
            if(nonprime==false){
                prime++;
                num+=2;
            }
        }
    }
    System.out.println("The nth prime number is: "+num);
    }
}

} }

Check this loop: 检查此循环:

for (int i=3; i <= square; i++){
        if (num % i == 0){
            num+=2;
        }
        else {
            prime++;
            num+=2;
        }
    }

It appears you want to loop through all odd numbers up to the square root of your number. 您似乎想遍历所有奇数,直到数字的平方根。 If one of them divides, then it should STOP the loop and mark it as a non-prime. 如果其中之一被除,则应停止循环并将其标记为非质数。 If it doesn't divide any number, you should mark it as a prime, but even that should be done after the loop has completed. 如果它不除以任何数字,则应将其标记为质数,但即使如此,也应在循环完成后执行。 (eg. when i > square) (例如,当我>正方形时)

I don't want to give you the answer as it appears you want to fix your existing loop yourself. 我不想给您答案,因为您似乎想自己修复现有的循环。 But one strategy is to mark it as a non-prime (in a boolean) for example, and then after the loop, check the boolean and increment your prime count (prime++) if the boolean indicates it is a prime. 但是一种策略是例如将其标记为非素数(以布尔值表示),然后在循环之后,检查布尔值,如果布尔值表示它是素数,则增加您的素数(素数++)。 Remember to reinitialize the boolean so that it will be set correctly next time it hits the for loop. 记住要重新初始化布尔值,以便下次遇到for循环时可以正确设置它。

Create another method to check whether number is prime or not and use while loop to get the primes. 创建另一个方法以检查数字是否为质数,并使用while循环获取质数。

public static void main(String[] args) {
    ...

    if (nthprime == 1) {
        System.out.println("The nth prime number is: 2");
    } else {
        int num = 3;

        for (int i = 2; i <= nthPrime; i++) {
            while(!isPrime(num)) {
                num += 2;
            }

            num += 2;
        }

        System.out.println("The nth prime number is: "+ (num - 2));
    }
}

private static boolean isPrime(int n) {
    int sqrt = (int) Math.sqrt(n);

    for (int i = 2; i <= sqrt; i++) {
        if (n % i == 0) {
            return false;
        }
    }

    return true;
}
import java.util.Scanner;
public class NewNthPrime {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int t = in.nextInt();
        for(int a0 = 0; a0 < t; a0++){
            boolean flag = false;
            int n = in.nextInt();
            int[] prime = new int[n];
            prime[0] = 2;
            int i = 3,j=1;

            while(j<n){
                for(int y=0;y<prime.length;y++){
                    if(prime[y]==0){
                        break;
                    }
                    else if (i%prime[y]==0){
                       flag = true;
                       break;
                    }
                }
                if(!flag){
                   prime[j++]=i;
                }
                flag =false;
                i+=2;
            }
            System.out.println(prime[n-1]);
        }
    }
}

here i declare an array named prime which stores all prime numbers. 在这里,我声明了一个名为prime的数组,该数组存储所有素数。 The while loop section checks whether any prime numbers which is stored in array-prime[] divides the number 'i' ( which are only odd no. ) or not. while循环部分检查存储在array-prime []中的质数是否除以数字“ i”( 仅是奇数 )。 If it does then flag becomes true and we skip for the next number 'i'. 如果确实如此,则标志变为true,我们跳过下一个数字“ i”。 Here inside while i also check if number inside array is zero then it break the for loop because we can't have any more prime numbers in prime array. 在这里,当我还检查数组内的数字是否为零时,它会中断for循环,因为在素数数组中不能再有素数了。 now if the number 'i' isn't divisible by any prime number which is in array then 'flag' remains false and 'i' put inside array prime[]. 现在,如果数字'i'不能被数组中的任何质数整除,则'flag'仍然为false,'i'放在数组prime []中。

Sorry, I haven't got time to look into your problem, but I think we can also find nth prime number this way as well:抱歉,我没有时间研究你的问题,但我认为我们也可以通过这种方式找到第 n 个素数:

public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println("Enter nth position for which you want to find prime number ");
    Scanner sc  = new Scanner(System.in);       
    int k = sc.nextInt();
    findnthprimenumber(k);  
}

private static void findnthprimenumber(int k) {
    // TODO Auto-generated method stub
    int count=0;
    int j=2;    
    int l =0;
    while(l<k){
        for(int i=2;i<=j/2;i++)
        {
            if(j%i != 0)                
                continue;               
            else 
                count++;                                                    
        } 
        if(count == 0) {
            if(l==(k-1))
            System.out.println("Prime number on "+ k +"th position is "+ j);
            l++;
        }
        count=0;
        j++;
    }
}

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

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