该程序要求用户提供大于 1 的最小数字和大于最小值的最大数字。然后它会逐个打印出它可以被什么整除,如果它是素数还是合数,以及它是否是这种格式的完美数:
2 is divisible by 1
2 is prime.
2 is not perfect
3 is divisible by 1
3 is prime.
3 is not perfect
4 is divisible by 1 2
4 is composite.
4 is not perfect.
5 is divisible by 1
5 is prime.
5 is not perfect
6 is divisible by 1 2 3
6 is composite.
6 is perfect.
最后它显示素数和完美数的数量。该程序有效,但我想知道是否有任何方法可以清理代码/使其更高效(或者如果我做错了什么)
代码:
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int min;
int max;
//declaring min and max values
System.out.println("Enter minimum value to check (an integer greater than 1:)");
min=input.nextInt();
while(!(min>1)) {
System.out.println("The entry is valid. Please be sure to enter an integer greater than 1");
System.out.println();
System.out.println("Enter minimum value to check (an integer greater than 1:)");
min=input.nextInt();
}
System.out.println("Enter maximum value to check (an integer greater than your min value:)");
max=input.nextInt();
while(!(max>min)) {
System.out.println("The entry is valid. Please be sure to enter an integer greater than the min value");
System.out.println();
System.out.println("Enter maximum value to check (an integer greater than min:)");
max=input.nextInt();
}
//declaring count and tracking variables
int count;
int numPrime=0;
int numPerfect=0;
int temp=1;
String result=" ";
boolean isPrime=true;
boolean isPerfect=false;
int i;
//main loop
for(count=min;count<=max;count++) {
for(i=2;i<=count;i++) {
if(count%i==0&&i!=count) {
isPrime=false;
result=result+i+" ";
temp+=i;
}
else
isPrime=true;
}
//Perfect counter
if(temp==count) {
isPerfect=true;
numPerfect=numPerfect+1;
}
else
isPerfect=false;
//Composite print
if(!(result.equals(" "))) {
System.out.println(count+" is divisible by 1"+result);
System.out.println(count+" is composite.");
if(isPerfect==true)
System.out.println(count+" is perfect.");
else
System.out.println(count+ " is not perfect.");
System.out.println();
}
//Prime print
else {
numPrime=numPrime+1;
System.out.println(count+" is divisible by 1");
System.out.println(count+" is prime.");
System.out.println(count+" is not perfect");
System.out.println();
}
//reset values
result=" ";
temp=1;
}
System.out.println("Primes found: "+numPrime);
System.out.println("Perfect numbers found: "+numPerfect);
}
}