在计算两个整数之间的质数时遇到麻烦

时间:2019-05-23 00:30:55

标签: java

我在获取给定整数A和整数B之间的所有素数时遇到问题。

问题在于输出结果远远超出了我为B定义的结果。我认为

if (isPrime){
    count++;

将解决此问题,但输出仍然远远超过整数B的预期数量。

例如,如果int valueA = 1int valueB = 100,它将在停止之前获得大约1到500的质数,而不仅仅是在100处结束支票。

谢谢您的帮助。

import java.util.*; 

public class PrimeNumbersTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner input = new Scanner(System.in); 

        // Ask user to input an integer value for A and B
        System.out.print("Enter the value of A (must be an integer): ");
        int valueA = input.nextInt();

        System.out.print("Enter the value of B (must be an integer): ");
        int valueB = input.nextInt();

        System.out.println("The prime numbers between " + valueA + " and " + valueB + " are:");

        final int LINE = 10;
        int count = valueA;
        int number = 2;

        while (count < valueB) {
        // Assume the number is prime   
        boolean isPrime = true;
        // Test if number is prime
        for (int divisor = 2; divisor <= number / 2; divisor++) {
            if (number % divisor == 0) { // If true number is not prime
                isPrime = false; // Set isPrime to false
                break; // Exit the for loop
            }
        }
         if (isPrime) {
             count++;

            if (count % LINE == 0) {
                System.out.println(number);
            }
            else 
                System.out.print(number + " ");

         }
         number++;
    }      
  }
}

1 个答案:

答案 0 :(得分:0)

当您要处理一定范围的数字时,请使用for循环而不是while循环,以减少混乱。您显然想要

for(int number = valueA; number <= valueB; number++){/*check if number is prime*/}

示例:

public static void main(String []args){
    int valueA = 1;
    int valueB = 100;
    int count = 0;
    for(int number = valueA; number <= valueB; number++)
    {
        if(isPrime(number))
        {
            count++;
            System.out.println(number);
        }
    }
    System.out.println("count = " + count);
}

public static boolean isPrime(int n)
{
    for(int i = 2; i*i <= n; i++)
    {
        if(n % i == 0)
        {
            return false;
        }
    }
    return n > 1;
}

对于您检查isPrime内联的要求:

public static void main(String []args){
    int valueA = 1;
    int valueB = 100;
    int count = 0;
    for(int number = valueA; number <= valueB; number++)
    {
        boolean isPrime = number > 1;
        for(int i = 2; i*i <= number; i++)
        {
            if(number % i == 0)
            {
                isPrime = false;
                break;
            }
        }
        if(isPrime)
        {
            count++;
            System.out.println(number);
        }
    }
    System.out.println("count = " + count);
}