简体   繁体   中英

Prime Number Program Problems

I'm currently working on a program in which the user inputs a number, and the program will give you the number of prime numbers up to that number. Although there are no errors, the program always outputs the same number: 3. This is the code:

public static int Prime(int num){
    boolean isPrime = true;
    int count = 0;
    for (int a = 2; a <=num; a++){ 
        for (int i = 2; i <= a/2; i++){
            if (a == 2 || a == 3 || a == 5){
                isPrime = true;
            }
            else if (a % i == 0){
                isPrime = false;
            }
        }
        if (isPrime == true)
            count++;
    }
    return count;
}

In your inner for loop, you are setting isPrime , but then you keep looping. Subsequent loops may set isPrime to false if a candidate divisor i doesn't divide cleanly. Only 2 , 3 , and 5 , the 3 numbers in your first if condition, set it to true always, so you always get 3 .

Instead, set isPrime to true at the beginning of the inner for loop, and break out of the inner for loop after each time you set isPrime . If the number is 2, 3, or 5, set to true and break so nothing can set it to false , so you can count it. If you found a factor, it's not prime, so set to false and break so nothing can set it to true and it's not counted.

Incidentally, your final if condition tests a boolean ; it can be simplified to if (isPrime) .

Your strategy is to test each number from 2 through num for primality by scanning for factors other than itself and 1. That's ok, albeit a bit simplisitic, but your implementation is seriously broken.

An approach involving scanning for factors implies that you start by guessing that the number being tested is prime, and then go looking for evidence that it isn't. You've missed the "guessing it's prime" part, which in your particular code would take the form of setting isPrime to true at the beginning of your outer loop.

Your code, on the other hand, never resets isPrime to true after testing the case of a == 5 . That variable will be set to false when testing the case of a == 6 , and will remain so for the duration. That is why you always get the result 3 for any input greater than 4.

If you properly reset isPrime in the outer loop then you can also remove the first part of the conditional in the inner loop, as it will be redundant. It is anyway never executed in the cases of a == 2 and a == 3 because the inner loop performs zero iterations in those cases.

Note also that it would be more efficient to break from the inner loop as soon as you determine that a is composite, and that you run more iterations of that loop than you need to do for primes (it would be sufficient to loop until i exceeds the square root of a ; that is, until i * i > a ).

Finally, note that this problem would be more efficiently implemented via the Seive of Eratosthenes (or one of the other prime number seives) as long as the numbers you want to test are not so large that the needed array would be prohibitively large.

I simplified your code by reducing number of operations which is needed to check if a is 2, 3, or 5.

public static int Prime(int num) {
        int count = 0;
        if (num >= 2) {
            count++; // One optimization here
        }
        for (int a = 3; a <= num; a+=2) {  // Another one here as we don't have any even number except 2 :D
            boolean isPrime = true;
            for (int i = 2; i <= a / 2; i++) {
                if (a % i == 0) {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) {
                count++;
            }
        }
        return count;
    }
#include <iostream>
using namespace std;


int numberOfPrimes(int num)
{
if(num==2)
  return 1;
else if(num<2)
  return 0;
int prime=1;

for(int i=3;i<=num;i++)
 {
    for(int j=2;j<=(i/2)+1;j++)
     {
        if(i%j==0)
           break;
         if(j==(i/2)+1)
          prime++;

     }

 }
 return prime;
}

package com.amit.primenumber;

public class PrimeNumber {

public static void main(String[] args) {
    long number=23L;
    String message=null;
    PrimeNumber primeNumber = new PrimeNumber();
    boolean result = primeNumber.primeNumber(number);
    if(result){
        message="a Prime Number";
    }else{
        message="Not a Prime Number";
    }

    System.out.println("The given "+number+" number is "+message);
}

public boolean primeNumber(long number){
    for(long i=2;i<=number/2;i++){
        if(number%i==0){
            return false;
        }   
    }
    return true;
}

}

package basics;

public class CheckPrimeOrNot {
    public void checkprimeNumber(int i){
        int flag=0;

        if(i>2){

            for(int j = 2; j <= i/2; j++){
                if(i%j == 0){
                    System.out.println("Given number is Not Prime");
                    flag=1;
                    break; 
                }
            }
            if(flag==0){
                System.out.println("Given number is Prime");
            }
        } else{
            System.out.println("Please enter a valid number");
        }
    }
    public static void main(String[] args) {
        CheckPrimeOrNot CheckNumber = new CheckPrimeOrNot();
        CheckNumber.checkprimeNumber(11);
        CheckNumber.checkprimeNumber(0);
        CheckNumber.checkprimeNumber(250365);
        CheckNumber.checkprimeNumber(1231);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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