如果你使用这个条件:if (index%2 != 0 && index%3 !=0),那么它永远不会考虑 2 或 3 个素数。如果您将其更改为:
if (index%2 != 0 && index%3 !=0 && index%5 !=0 && index%7 !=0)
它不会发现 2、3、5 或 7 是素数。
我更正了您的算法并决定使用ArrrayList 来存储素数列表,因为大小是动态的。否则,我们将首先必须找到您所在区域的素数数量以确定数组的大小,然后再执行相同的循环,除了这次将数字添加到数组中。
一旦你找到一个素数。使用nameOfArrayList.add(primeNumberFound);。
_____________ __________________ _________________ _________________________________
用 ArrayList 来做
public class QC3PrimeNumbers
{
public static void main (String[] args)
{
System.out.println ("Here are the prime numbers: ");
// use a List to store your prime numbers (its size is dynamic)
List<Integer> primeNums = new ArrayList<Integer>();
for (int index = 2; index < 100; index++)
{
boolean isPrime = true; // initially true, and reset this every loop
// for every number that can factor into the index number
for (int i = 2; i < index; i++)
// if a number is found that factors into it, it's not prime
if (index%i == 0) isPrime = false;
if (isPrime) // if this current index number is prime
{
System.out.print (index + " ");
primeNums.add(index); // add it to the List
}
}
}
}
_____________ __________________ _________________ _________________________________
用一个普通的数组来做
以下是使用常规数组的方法(但不推荐):
public class QC3PrimeNumbers
{
public static void main (String[] args)
{
System.out.println ("Here are the prime numbers: ");
int numOfPrimes = 0; // counts the # of prime nums in your region
// this loop will count up the number of prime numbers
for (int index = 2; index < 100; index++)
{
boolean isPrime = true; // initially true, reset this every loop
// for every number that can factor into the index number
for (int i = 2; i < index; i++)
// if a number is found that factors into it, it's not prime
if (index % i == 0) isPrime = false;
if (isPrime) // if this number is prime
numOfPrimes++; // add it to the count
}
// array to hold the prime nums w/ size=how many prime nums we counted
int[] primeNums = new int[numOfPrimes];
int count = 0; // keep track of the position in the primeNums array
for (int index = 2; index < 100; index++)
{
boolean isPrime = true; // initially true, reset this every loop
// for every number that can factor into the index number
for (int i = 2; i < index; i++)
// if a number is found that factors into it, it's not prime
if (index % i == 0) isPrime = false;
if (isPrime) // if this number is prime
{
primeNums[count] = index; // add this prime num to the array
count++; // change the array position tracker for next number
}
}
for (int n : primeNums) // for every integer in primeNums array
System.out.print(n + " "); // display that integer to the console
}
}