一个更短的方法。
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static List primeFactors(int numbers) {
int n = numbers;
List factors = new ArrayList();
for (int i = 2; i <= n / i; i++) {
while (n % i == 0) {
factors.add(i);
n /= i;
}
}
if (n > 1) {
factors.add(n);
}
return factors;
}
public static void main(String[] args)
{
System.out.println("Please enter two integers : ");
Scanner input = new Scanner(System.in);
int num1 = input.nextInt();
int num2 = input.nextInt();
List primenos = new ArrayList();
List result;
for(int i=num1; i<=num2; i++)
{
result = primeFactors(i);
System.out.print(i +":");
if(result.size()==1 && result.get(0)==i)
{
System.out.println(" prime");
primenos.add(i);
}
else
{
for (Integer j : result) {
System.out.print(" "+j);
}
}
System.out.println();
}
System.out.println("There are "+primenos.size()+" prime numbers");
int total = 0;
for(Integer j : primenos)
{
total+=j;
}
System.out.println("The average value of the prime numbers is "+total/primenos.size());
}
}这只是一种方法。
如果你谷歌,你可以找到数百种算法。找到一个并根据您的需求进行修改。