仅在Java中打印两个给定数字之间的所有素数

时间:2022-10-21 11:24:03

everyone, I tried this program but not get the expected answer, Please help me out.

大家,我试过这个程序但没有得到预期的答案,请帮帮我。

Question is:

问题是:

Print all prime numbers between two given numbers. For example: Function is Prime(beg,end), for Prime(4,7) it will return {5,7}, for Prime(7,16) it will return {7,11,13}. My code :

打印两个给定数字之间的所有素数。例如:Function为Prime(beg,end),对于Prime(4,7),它将返回{5,7},对于Prime(7,16),它将返回{7,11,13}。我的代码:

package com.robin.practise;

import java.util.Scanner;

public class PrimebetweenRange 
{

    private static String Prime(int beg, int end)
    {
        String res= " ";
        for(int i= beg; i<= end; i++)
        {
            for(int j=2; j<= end; j++)
            {
                if(i%j!= 0)
                {
                    //System.out.println(i+  " ");
                    res= i+ " ";
                }
            }
        }
        return res;
    }

    public static void main(String[] args) 
    {
        Scanner scn= new Scanner(System.in);
        System.out.println("Enter any two numbers: ");
        int n1= scn.nextInt();
        int n2= scn.nextInt();
        scn.close();
        System.out.println(Prime(n1, n2));
    }
}

4 个解决方案

#1


1  

You cannot decide that a number if prime if it is not divisible by a number. You need to add to the result at the end of the inner loop.

如果数字不能被数字整除,则无法确定数字是否为素数。您需要在内循环结束时添加结果。

There are quite a few problems in your code. Here's the working one

您的代码中存在很多问题。这是工作的

for(int i= beg; i<= end; i++) {
    boolean prime = true;  //start by assuming the current number is prime
    for(int j=2; j<i; j++) { // Loop till j < i
        if(i%j == 0) {
          prime = false; //Set the current number as not prime if it is divisible by any number lesser than it
        }
   }
   if (prime) {
       res += i+ " ";   //Add to result
   }
}

Note: As sanit@ answer says, you can terminate the loop much earlier. Refer to this to know why looping till square root of the number is enough.

注意:正如sanit @ answer所说,你可以更早地终止循环。请参阅此以了解为什么循环直到数字的平方根已足够。

#2


0  

The answers above aren't enough to solve this. At any run of the second loop, you wanna check if the i enter every if of any j. Define a boolean,for each i, check if for each j if j is dividing him, (while j isn't i itself). If so, then don't do anything, and keep running.Otherwise, concatenate i with the res so far, and print it at the end;

上面的答案不足以解决这个问题。在第二个循环的任何运行中,你想检查我是否输入任何j的每一个。定义一个布尔值,对于每个i,检查每个j是否j正在划分他,(而j不是我自己)。如果是这样,那么就不要做任何事情,并继续运行。否则,到目前为止,我与res连接,并在最后打印它;

boolean flag=true;
for(int i= beg; i<= end; i++)
    {
        for(int j=2; j<= end; j++)
        {
            if(i%j== 0 && i!=j)
            {
                flag=true;
                res= i+ " ";
            }
        }
    if(!flag){
      res+=i +" ";}
    flag=false;
    }
    return res;
}

#3


0  

private static String Prime(int beg, int end) {
    String res = " ";
    outer: for (int i = beg; i <= end; i++) {
        int upto = (int) Math.sqrt(end);
        for (int j = 2; j <= upto; j++) {
            if (i != j && i % j == 0) {
                continue outer;
            }
        }
        System.out.println(i + " ");
    }
    return res;
}

I have optimized the code little bit using Math.sqrt, you can still do some more optimization, just google how to optimize prime number genearation.

我使用Math.sqrt对代码进行了一些优化,您仍然可以进行更多优化,只需谷歌如何优化素数生成。

#4


0  

Here is a working solution:

这是一个有效的解决方案:

public static void primeBetween(int beg, int end) {
        List<Integer> result = new ArrayList<Integer>();
        for (int n = beg; n <= end; n++) {
            boolean prime = true;
            for (int j = 2; j <= n / 2; j++) {
                if (n % j == 0 && n != j) {
                    prime = false;
                }
            }
            if (prime) {
                result.add(n);
            }
        }
        System.out.println(result);
    }

    /* Driver program  */
    public static void main(String[] args) {
        primeBetween(2, 25);
    }

This is the output: [2, 3, 5, 7, 11, 13, 17, 19, 23]

这是输出:[2,3,5,7,11,13,17,19,23]

#1


1  

You cannot decide that a number if prime if it is not divisible by a number. You need to add to the result at the end of the inner loop.

如果数字不能被数字整除,则无法确定数字是否为素数。您需要在内循环结束时添加结果。

There are quite a few problems in your code. Here's the working one

您的代码中存在很多问题。这是工作的

for(int i= beg; i<= end; i++) {
    boolean prime = true;  //start by assuming the current number is prime
    for(int j=2; j<i; j++) { // Loop till j < i
        if(i%j == 0) {
          prime = false; //Set the current number as not prime if it is divisible by any number lesser than it
        }
   }
   if (prime) {
       res += i+ " ";   //Add to result
   }
}

Note: As sanit@ answer says, you can terminate the loop much earlier. Refer to this to know why looping till square root of the number is enough.

注意:正如sanit @ answer所说,你可以更早地终止循环。请参阅此以了解为什么循环直到数字的平方根已足够。

#2


0  

The answers above aren't enough to solve this. At any run of the second loop, you wanna check if the i enter every if of any j. Define a boolean,for each i, check if for each j if j is dividing him, (while j isn't i itself). If so, then don't do anything, and keep running.Otherwise, concatenate i with the res so far, and print it at the end;

上面的答案不足以解决这个问题。在第二个循环的任何运行中,你想检查我是否输入任何j的每一个。定义一个布尔值,对于每个i,检查每个j是否j正在划分他,(而j不是我自己)。如果是这样,那么就不要做任何事情,并继续运行。否则,到目前为止,我与res连接,并在最后打印它;

boolean flag=true;
for(int i= beg; i<= end; i++)
    {
        for(int j=2; j<= end; j++)
        {
            if(i%j== 0 && i!=j)
            {
                flag=true;
                res= i+ " ";
            }
        }
    if(!flag){
      res+=i +" ";}
    flag=false;
    }
    return res;
}

#3


0  

private static String Prime(int beg, int end) {
    String res = " ";
    outer: for (int i = beg; i <= end; i++) {
        int upto = (int) Math.sqrt(end);
        for (int j = 2; j <= upto; j++) {
            if (i != j && i % j == 0) {
                continue outer;
            }
        }
        System.out.println(i + " ");
    }
    return res;
}

I have optimized the code little bit using Math.sqrt, you can still do some more optimization, just google how to optimize prime number genearation.

我使用Math.sqrt对代码进行了一些优化,您仍然可以进行更多优化,只需谷歌如何优化素数生成。

#4


0  

Here is a working solution:

这是一个有效的解决方案:

public static void primeBetween(int beg, int end) {
        List<Integer> result = new ArrayList<Integer>();
        for (int n = beg; n <= end; n++) {
            boolean prime = true;
            for (int j = 2; j <= n / 2; j++) {
                if (n % j == 0 && n != j) {
                    prime = false;
                }
            }
            if (prime) {
                result.add(n);
            }
        }
        System.out.println(result);
    }

    /* Driver program  */
    public static void main(String[] args) {
        primeBetween(2, 25);
    }

This is the output: [2, 3, 5, 7, 11, 13, 17, 19, 23]

这是输出:[2,3,5,7,11,13,17,19,23]