3

I'm having trouble writing a program that finds the prime numbers between 2-50. My program right now finds "mostly" prime numbers but some non-prime numbers are included. I know there are way more effective methods and strategies for finding prime numbers but I'm trying to first run through every possibility before i move onto more efficient and effective strategies. The way the program is written now if it does find a prime number it prints it multiple times when I only want it to be printed once. Is my program conceptually correct or is my rationale flawed. Why does my program mostly find prime numbers but throw in some non prime numbers? Why does my program print the prime numbers multiple times?

Here is my approach to the problem.

  1. create a for loop to represent potential prime numbers between 2-50. Represent these potential prime numbers by the variable "i". This loop will count down from 50.

  2. Since a number is prime only if there are no other divisible numbers besides itself and 1, i want to create a inner for loop to divide i by every possible number between 2 and i -1 to see if any of these numbers divides evenly into i. Represent these possible divisors by the variable j. If at any point j does divides evenly into i it's not a prime number so I want my inner loop to exit.

  3. If i gets divided by all the numbers of j and there are no numbers that divide evenly into i then that number if prime and want to print that number.

*

import acm.program.*;
public class PrimeNumber extends ConsoleProgram{
public void run(){

  for (int i =50; i >= 2; i--){
    for (int j= 2; j < i-1; j++){

        if (i % j >= 1){
         println(i);
         }else{
         if (i % j == 0) break;
                }
              } /*end of inner loop */  
           } /* end of for loop */

       } /* end of run method */
     } 
4

7 に答える 7

1

You correctly observed that if a number i can be evenly divided by a number j, then i % j == 0.

However, you're printing i every time you find a case where i % j >= 0 -- that doesn't mean however thati is prime, because there could be some other j that i can be evenly divided by.

Instead, you should first go through all of your j, and only if none of them gives you == 0, should you consider i prime. You could use a boolean variable isPrime that is initially true, but that the inner for-loop sets to false as soon as it finds a j by which i can be evenly divided.

于 2013-05-24T02:01:43.190 に答える
1

2 番目のループ (内側のループ) にバグがあります。

j....ではなく、インクリメントする必要がありiます。つまり、内側のループは

for (int j= 2; j < i-1; j++){

そしてそうではない

for (int j= 2; j < i-1; i++){
于 2013-05-24T02:03:15.870 に答える