简体   繁体   English

素数Java程序

[英]Java Program for Prime numbers

Problem 问题

In this project you will write a Java program that reads a positive integer n from standard input, then prints out the first n prime numbers. 在这个项目中,您将编写一个Java程序,该程序从标准输入中读取一个正整数n,然后打印出前n个素数。 We say that an integer m is divisible by a non-zero integer d if there exists an integer k such that m = kd , ie if d divides evenly into m. 我们说,如果存在整数k使得m = kd,则整数m可被非零整数d整除,即,如果d被均分为m。 Equivalently, m is divisible by d if the remainder of m upon (integer) division by d is zero. 等效地,如果将m的整数除以d,则m可被d整除。 We would also express this by saying that d is a divisor of m. 我们也可以通过说d是m的除数来表达这一点。 A positive integer p is called prime if its only positive divisors are 1 and p. 如果正整数p的唯一正数为1和p,则称其为质数。 The one exception to this rule is the number 1 itself, which is considered to be non-prime. 此规则的一个例外是数字1本身,它被视为非素数。 A positive integer that is not prime is called composite. 非素数的正整数称为复合。 Euclid showed that there are infinitely many prime numbers. 欧几里得表明有无限多个质数。 The prime and composite sequences begin as follows: 素数和复合序列如下所示:

Primes: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, … 

Composites: 1, 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25, 26, 27, 28, … 

There are many ways to test a number for primality, but perhaps the simplest is to simply do trial divisions. 有很多方法可以测试数字的素数,但最简单的方法就是简单地进行除法运算。 Begin by dividing m by 2, and if it divides evenly, then m is not prime. 首先将m除以2,如果将其平均除,则m不是质数。 Otherwise, divide by 3, then 4, then 5, etc. If at any point m is found to be divisible by a number d in the range 2 dm−1, then halt, and conclude that m is composite. 否则,除以3,然后除以4,然后除以5,以此类推。如果发现在任意一点处,m可被2 dm-1范围内的数字d整除,则停止,并得出m是复合的结论。 Otherwise, conclude that m is prime. 否则,得出m为质数的结论。 A moment's thought shows that one need not do any trial divisions by numbers d which are themselves composite. 片刻的想法表明,人们不必对本身是合成数字d进行任何试除。 For instance, if a trial division by 2 fails (ie has non-zero remainder, so m is odd), then a trial division by 4, 6, or 8, or any even number, must also fail. 例如,如果试验除以2失败(即余数非零,因此m为奇数),则试验除以4、6或8或任何偶数也将失败。 Thus to test a number m for primality, one need only do trial divisions by prime numbers less than m. 因此,为了测试数字m的素数,只需用小于m的素数进行试除。 Furthermore, it is not necessary to go all the way up to m−1. 此外,不必一直上升到m-1。 One need only do trial divisions of m by primes p in the range 2 pm . 只需在2 pm范围内对m除以质数p进行试验除法。 To see this, suppose m >1 is composite. 为了看到这一点,假设m> 1是复合的。 Then there exist positive integers a and b such that 1 < a < m, 1 < b < m, and m = ab . 然后存在正整数a和b,使得1 <a <m,1 <b <m,并且m = ab。 But if both a > m and b > m , then ab > m, contradicting that m = ab . 但是如果a> m和b> m,则ab> m,这与m = ab相矛盾。 Hence one of a or b must be less than or equal to m . 因此,a或b之一必须小于或等于m。

To implement this process in java you will write a function called isPrime() with the following signature: 为了在Java中实现此过程,您将编写一个带有以下签名的名为isPrime()的函数:

static boolean isPrime(int m, int[] P) 

This function will return true or false according to whether m is prime or composite. 该函数将根据m是质数还是复合数返回true或false。 The array argument P will contain a sufficient number of primes to do the testing. 数组参数P将包含足够数量的质数以进行测试。 Specifically, at the time isPrime() is called, array P must contain (at least) all primes p in the range 2 pm . 具体来说,在调用isPrime()时,数组P必须包含(至少)2 pm范围内的所有素数p。 For instance, to test m = 53 for primality, one must do successive trial divisions by 2, 3, 5, and 7. We go no further since 11 > 53 . 例如,要测试m = 53的素数,必须连续进行2、3、5和7的除法。自11> 53以来,我们不再赘述。 Thus a precondition for the function call isPrime(53, P) is that P[0] = 2 , P[1] = 3 , P[2] = 5, and P[3] = 7 . 因此,函数调用isPrime(53,P)的前提是P [0] = 2,P [1] = 3,P [2] = 5和P [3] = 7。 The return value in this case would be true since all these divisions fail. 由于所有这些除法都会失败,因此这种情况下的返回值将为true。 Similarly to test m =143 , one must do trial divisions by 2, 3, 5, 7, and 11 (since 13 > 143 ). 与测试m = 143相似,必须进行2、3、5、7和11的除法运算(因为13> 143)。 The precondition for the function call isPrime(143, P) is therefore P[0] = 2 , P[1] = 3 , P[2] = 5, P[3] = 7 , and P[4] =11. 因此,函数调用的前提是Prime(143,P)为P [0] = 2,P [1] = 3,P [2] = 5,P [3] = 7和P [4] = 11。 The return value in this case would be false since 11 divides 143. Function isPrime() should contain a loop that steps through array P, doing trial divisions. 在这种情况下,返回值将为false,因为11除以143。函数isPrime()应该包含一个循环,该循环逐步遍历数组P,进行尝试除法。 This loop should terminate when 2 either a trial division succeeds, in which case false is returned, or until the next prime in P is greater than m , in which case true is returned. 当2尝试除法成功后,此循环应终止,在这种情况下将返回false,或者直到P中的下一个素数大于m为止,在这种情况下将返回true。 Function main() in this project will read the command line argument n, allocate an int array of length n, fill the array with primes, then print the contents of the array to stdout according to the format described below. 该项目中的函数main()将读取命令行参数n,分配一个长度为n的int数组,用质数填充该数组,然后根据下面描述的格式将数组的内容打印到stdout。 In the context of function main(), we will refer to this array as Primes[]. 在函数main()的上下文中,我们将此数组称为Primes []。 Thus array Primes[] plays a dual role in this project. 因此,数组Primes []在此项目中扮演双重角色。 On the one hand, it is used to collect, store, and print the output data. 一方面,它用于收集,存储和打印输出数据。 On the other hand, it is passed to function isPrime() to test new integers for primality. 另一方面,将其传递给函数isPrime()以测试新整数的素性。 Whenever isPrime() returns true, the newly discovered prime will be placed at the appropriate position in array Primes[]. 每当isPrime()返回true时,新发现的素数将被放置在数组Primes []中的适当位置。 This process works since, as explained above, the primes needed to test an integer m range only up to m , and all of these primes (and more) will already be stored in array Primes[] when m is tested. 该过程之所以有效,是因为如上所述,测试整数m范围至m所需的质数,并且在测试m时,所有这些质数(以及更多)将已经存储在数组Primes []中。 Of course it will be necessary to initialize Primes[0] = 2 manually, then proceed to test 3, 4, … for primality using function isPrime(). 当然,有必要手动初始化Primes [0] = 2,然后使用函数isPrime()对素数进行测试3,4,…。

The following is an outline of the steps to be performed in function main(). 下面是函数main()中要执行的步骤的概述。

  • Check that the user supplied exactly one command line argument which can be interpreted as a positive integer n. 检查用户是否正确提供了一个命令行参数,该参数可以解释为正整数n。 If the command line argument is not a single positive integer, your program will print a usage message as specified in the examples below, then exit. 如果命令行参数不是单个正整数,则程序将按照以下示例中的说明打印用法消息,然后退出。
  • Allocate array Primes[] of length n and initialize Primes[0] = 2 . 分配长度为n的数组Primes []并初始化Primes [0] = 2。
  • Enter a loop which will discover subsequent primes and store them as Primes[1] , Primes[2], Primes[3] , ..., Primes[n −1] . 输入一个循环,该循环将发现后续的素数并将其存储为Primes [1],Primes [2],Primes [3],...,Primes [n -1]。 This loop should contain an inner loop which walks through successive integers and tests them for primality by calling function isPrime() with appropriate arguments. 该循环应包含一个内部循环,该循环遍历连续的整数,并通过调用具有适当参数的函数isPrime()来测试它们的素性。
  • Print the contents of array Primes[] to stdout, 10 to a line separated by single spaces. 将Primes []数组的内容打印到stdout,将10打印到由单个空格分隔的行。 In other words Primes[0] through Primes[9] will go on line 1, Primes[10] though Primes[19] will go on line 2, and so on. 换句话说,Primes [0]到Primes [9]将在第1行,Primes [10]尽管Primes [19]将在第2行,依此类推。 Note that if n is not a multiple of 10, then the last line of output will contain fewer than 10 primes. 请注意,如果n不是10的倍数,则输出的最后一行将包含少于10个素数。

Your program, which will be called Prime.java, will produce output identical to that of the sample runs below. 您的程序将称为Prime.java,将产生与下面的示例运行相同的输出。 (As usual % signifies the unix prompt.) (通常,%表示Unix提示符。)

% java Prime 
Usage: java Prime [PositiveInteger] 
% java Prime xyz 
Usage: java Prime [PositiveInteger] 
% java Prime 10 20 
Usage: java Prime [PositiveInteger] 
% java Prime 75 
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 
% 
3 

As you can see, inappropriate command line argument(s) generate a usage message which is similar to that of many unix commands. 如您所见,不合适的命令行参数会生成用法消息,该消息与许多unix命令的用法消息相似。 (Try doing the more command with no arguments to see such a message.) Your program will include a function called Usage() having signature (尝试执行不带参数的more命令以查看此类消息。)您的程序将包括一个具有签名的名为Usage()的函数。

static void Usage() 

that prints this message to stderr, then exits. 将此消息打印到stderr,然后退出。 Thus your program will contain three functions in all: main(), isPrime(), and Usage(). 因此,您的程序将总共包含三个函数:main(),isPrime()和Usage()。 Each should be preceded by a comment block giving it's name, a short description of it's operation, and any necessary preconditions (such as those for isPrime().) See examples on the webpage. 每个注释之前都应加一个注释块,给出其名称,其操作的简短描述以及任何必要的前提条件(例如isPrime()的前提条件。)请参见网页上的示例。

Attempted Solution 尝试的解决方案

class Prime {
    public static void main(String[] args) {
        int num1 = 0;
        int num2 = 0;
        int num3;
        for (num1 = 1; num1 < 101; num1++)
            System.out.println(num1);
        for (num2 = 1; num2 < 101; num1++)
            System.out.println(num2);
        num3 = num2 % num1;
        if (num3 == 0)
            System.out.println("The prime numbers are " + num1);
        else
            System.out.println("The prime numbers are " + (num1 += 1));
    }
}

Ben, it looks like you are attempting something that is far beyond your current capability. Ben,看来您正在尝试的事情远远超出了您当前的能力。 Start with some much simpler problems. 从一些简单得多的问题开始。 Talk to your teacher and consider taking a more rudimentary course. 与您的老师交谈,并考虑参加更基础的课程。 You don't appear to understand either what the program is supposed to do, or how to write a program that might satisfy the requirements, and nothing we say here can overcome that - you have to develop more understanding of math and programming. 您似乎既不了解程序应该做什么,也不了解如何编写可能满足要求的程序,而我们在这里所说的没有什么可以克服的-您必须对数学和编程有更多的了解。 We're happy to help with that, but just writing your program here won't help you, and you are too far away from a solution for suggestions to help. 我们很乐意为您提供帮助,但是仅在此处编写程序将无济于事,并且您离解决方案的建议还很遥远。 I'm sorry if this sounds harsh; 如果这听起来很刺耳,我感到抱歉。 honestly, I mean it constructively. 老实说,我的意思是建设性的。 Please stay with it - but start simpler. 请继续使用-但要简单一些。

Your example solution doesn't really follow the problem's specification at all. 您的示例解决方案根本没有真正遵循问题的规范。 You should focus first on writing the static boolean isPrime(int m, int[] P) method. 您应该首先专注于编写static boolean isPrime(int m, int[] P)方法。 All that method needs to do is: 该方法所需要做的就是:

  • Iterate over the contents of P 遍历P的内容
  • If an element evenly divides m , m is composite -- return false 如果一个元素将m平均除,则m是合成的-返回false
  • If an element's square is greater than m , m is prime -- return true . 如果元素的平方大于m ,则m为质数-返回true It sounds like from the problem description this won't ever happen, P will only have the primes from 2 to the one just before crossing the sqrt(m) boundary 从问题描述中听起来这永远不会发生, P仅在跨越sqrt(m)边界之前具有从2到1的质数。
  • If all the elements of P have been tested, m is prime -- return true 如果已经测试了P所有元素,则m为质数-返回true

After that you can write main to make the primes array and build it up using the described loop, and finally do argument checking and implement the static void Usage() function to call if the arguments are invalid 之后,您可以编写main来制作素数数组并使用所描述的循环对其进行构建,最后进行参数检查并实现static void Usage()函数以在参数无效时调用

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

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