简体   繁体   English

Java Prime数字方法

[英]Java Prime Number Method

The question is exactly as follows: 问题完全如下:

Write a method that determines whether a number is prime. 编写一个确定数字是否为素数的方法。 Then use this method to write an application that determines and displays all the prime numbers less than 10,000. 然后使用此方法编写一个应用程序,确定并显示小于10,000的所有素数。

I have already written a program that finds all prime numbers up to 10,000, but then found a simpler and more efficient one on StackOverflow, and that is this: 我已经编写了一个程序,可以找到所有素数高达10,000,但随后在StackOverflow上找到了一个更简单,更高效的程序,就是这样:

package prime;

import java.util.Scanner;

public class Prime 
{
    public static void main(String[] args) 
    {
        for(int i = 1; i <= 10000; i++)
        {
            int factors = 0;
            int j = 1;

            while(j <= i)
            {
                if(i % j == 0)
                {
                    factors++;
                }
                j++;
            }
            if (factors == 2)
            {
                System.out.println(i);
            }
        }
    }
}

Since I am very new to Java and am especially not good at methods, this problem is especially difficult for me. 由于我对Java非常陌生并且特别不擅长方法,因此这个问题对我来说尤其困难。 I tried making a method, but nothing is being returned, and when I try to return something I get error after error after error. 我尝试制作一个方法,但没有返回任何内容,当我尝试返回某些内容时,我在错误发生错误后收到错误。

The help I need is mainly just Pseudo-Code for what I should do to tackle this problem; 我需要的帮助主要是伪代码,我应该做些什么来解决这个问题; I'm not asking you for the answer, I'm just asking for a start. 我不是在问你答案,我只是要求一个开始。

package prime;

public class Prime 
{
    public static void main(String[] args) 
    {
       for(int i = 1; i <= 10000; i++)
       {
         if (isPrimeNumber(i))
         {
            System.out.println(i);
         }
       }
    }


    public static boolean isPrimeNumber(int i) {
        int factors = 0;
        int j = 1;

        while(j <= i)
        {
            if(i % j == 0)
            {
                factors++;
            }
            j++;
        }
        return (factors == 2);
  }
}

Write a method that determines whether a number is prime. 编写一个确定数字是否为素数的方法。 Then use this method to write an application that determines and displays all the prime numbers less than 10,000. 然后使用此方法编写一个应用程序,确定并显示小于10,000的所有素数。

It seems to me that you need a method that returns true if the number you pass it is prime and false otherwise. 在我看来,如果传递的数字是素数,则需要一个返回true的方法,否则返回false。 So, all you really need to do here is to move the portion of the code that deals with determining if a number is prime and, inside that method, instead of printing the number when it is prime, return true, otherwise return false. 所以,你真正需要做的就是移动处理确定一个数字是否为素数的代码部分,并且在该方法中,而不是在它是素数时打印数字,返回true,否则返回false。 Then, inside the main method, print the number if that function indicates that the current integer is prime (by returning true) or do nothing otherwise. 然后,在main方法内部,如果该函数指示当前整数是素数(通过返回true),则打印数字,否则不执行任何操作。 This is the best I can do to explain the solution without giving you the actual code. 这是我能解释解决方案而不给你实际代码的最佳方法。

EDIT:Since you asked for pseudocode: 编辑:因为你要求伪代码:

main() 
   for i in 1..10000 :
     if isPrime(i)
        print i


isPrime(i):
    factors = 0
    num = 1

    while num is less than or equal to i:
        if i mod nums is 0:
            increment factors
        increment nums
    return (factors == 2) 
public boolean isPrime(long num)
{
   double limit = Math.sqrt(num);
   for (long i = 2; i < limit; i++)
       if(num%i == 0)
           return false;
   return true;
}

I have found one more solution using java streams: 我找到了一个使用java流的解决方案:

import java.util.stream.LongStream;

public static boolean isPrime(long num) {
    return num > 1 && LongStream.rangeClosed(2, (long)Math.sqrt(num)).noneMatch(div-> num % div== 0);
}

Here goes a test case to prove this works: 这里有一个测试用例来证明这是有效的:

// First 168 primes, retrieved from https://en.wikipedia.org/wiki/Prime_number
private static final List<Integer> FIRST_168_PRIMES =
        Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997);

@Test
public void testNumberIsPrime() {
    FIRST_168_PRIMES.stream().forEach(integer -> assertTrue(isPrime(integer)));
}

@Test
public void testNumberIsNotPrime() {
    List<Integer> nonPrime = new ArrayList<>();
    for (int i = 2; i < 1000; i++) {
        if (!FIRST_168_PRIMES.contains(i)) {
            nonPrime.add(i);
        }
    }

    nonPrime.stream().forEach(integer -> assertFalse(isPrime(integer)));
}
/**
* List all prime numbers from 101 to 200
* for responding your question, I think it is a good view to have it done
* @ Joannama
*
*/

public class PrimeNum
{
    public static void main(String[] args)
    {
        for ( int i = 101; i <= 200 ; i += 2)
        {
            // get rid of even number from 101 to 200
            //because even number are never a prime number
            boolean f = true;

            //assume these numbers are prime numbers
            for ( int j = 2; j < i; j++)
            {
                if ( i % j == 0)
                {
                    f = false;
                    // if the reminder = 0,
                    //which means number is not a prime,
                    //therefore f = false and break it
                    break;
                }
            }
            if ( ! f)
            {
                continue;
            }
            System.out.print("\u0020" + i);
        }
    }
}

As the Brenann posted. 正如Brenann所说。 Best way to calculate if its a prime, but with only one correction to the limit. 计算它是否为素数的最佳方法,但只有一次校正到极限。 You must add 1 to it, or it detects false positives. 您必须向其添加1,否则它会检测误报。

public boolean isPrime(long num){
   double limit = Math.sqrt(num) + 1;
   for (long i = 2; i < limit; i++)
       if(num%i == 0)
           return false;
   return true;
}

just be sure to start with 3 一定要从3开始

Dragoslav Petrovic solution is ok, but it returns bad result when passing 2 as input, which is also a prime number. Dragoslav Petrovic解决方案没问题,但是当输入2作为输入时它返回错误的结果,这也是一个素数。 This is how I resolved it: 这是我解决它的方式:

public boolean isPrime(int number) {

    if (number <= 1) {
        System.out.println("Only positive numbers above 1 can be prime.");
        return false;
    }

    double limit = Math.sqrt(number);

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

    return true;
}
static int primeNumber(int n){
  int i = 1, factor = 0;
  while(i <= n){
  if(n % i == 0){
  factor++;
  }
  i++;
  }
  if (factor == 2){
  return 1;
  }
   return 0;
  }

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

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