Java 数组中的素数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21231150/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 07:29:39  来源:igfitidea点击:

Prime numbers in array

javaarraysprimes

提问by user3214606

I need to write a function that recieve from the user a number(n), and the function return an array with all the prime numbers until the user number(n). I know how to write the function that check if number is prime, but i dont know how to enter the numbers to an array.. for example if the user entered 53, it will return [2 ,3 ,5 ,7 ,11 ,13 ,17 ,19 ,23 ,29 ,31 ,37 ,41 ,43 ,47 ,53]. I forgot to tell that the language is java.. my bad!

我需要编写一个从用户那里接收一个数字(n)的函数,该函数返回一个包含所有素数的数组,直到用户编号(n)。我知道如何编写检查数字是否为素数的函数,但我不知道如何将数字输入到数组中。例如,如果用户输入 53,它将返回 [2 ,3 ,5 ,7 ,11 , 13,17,19,23,29,31,37,41,43,47,53]。我忘了说语言是 java .. 我的错!

回答by barak manos

Here is one way to do it (you did not specify language, so I'm using Python):

这是一种方法(您没有指定语言,所以我使用的是 Python):

def GetPrimes(n):
    array = []
    for i in range(2,n+1):
        if IsPrime(i):
            array.append(i)
    return array

def IsPrime(n):
    for i in range(2,n/2+1):
        if n % i == 0:
            return False
    return True

print GetPrimes(53)

回答by Dmitry Bychenko

Usually, you can'tchange array length, so you should use the appropriate collection where you can add items; that is List<>in C#, ArrayList<>in Java etc.

通常,您无法更改数组长度,因此您应该使用适当的集合来添加项目;这是List<>在C#,ArrayList<>Java中等等。

Technically, you can implement separate IsPrimemethod and then check the integers in 2..maxrange, but here it can just be inlined.

从技术上讲,您可以实现单独的IsPrime方法,然后检查2..max范围内的整数,但在这里它可以内联。

Possible code in C#

C#中可能的代码

public static int[] GetPrimes(int max) {
  if (max <= 1)
    return new int[0];
  else if (max == 2) // <- let's process the only even prime (2) separately
    return new int[] { 2 };

  List<int> primes = new List<int>() { 2, 3 };

  // Sieve through odd numbers:    
  for (int i = 5; i <= max; i += 2) {
    int sqrt = (int) Math.Sqrt(i + 1);

    Boolean isPrime = true;

    // There's no need to check if (i % primes[0] == 0):
    // primes[0] == 2, and loop is for odd numbers - 5, 7, 9,...
    for (int j = 1; primes[j] <= sqrt; ++j)
      if ((i % primes[j]) == 0) {
        isPrime = false;
        break;
      }

    if (isPrime)
      primes.Add(i);
  }

  return primes.ToArray();
}
// ....
// Test will return the string
// "2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53"
String result = String.Join(", ", GetPrimes(53).Select(x => x.ToString()));

回答by Tushar Thakur

Here is the code

这是代码

private ArrayList getPrimeNumbers(int number)
{
    ArrayList primeNumbers = new ArrayList();
    for (int i = 0; i <= number; i++)
    {
        if(isPrime(i)) 
        {
            primeNumbers.add(i);
        }
    }
    return primeNumbers;
} 


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