【发布时间】:2017-10-13 06:33:27
【问题描述】:
此程序要求用户提供大于 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);
}
}
【问题讨论】:
-
如果您的代码有效,那么我建议将其发布在code review
-
好的,谢谢!
-
既然是作业,我不想破坏学习机会,但是您认为可以减少 for 循环的迭代次数吗?具体来说,for(i=2;i
-
@JustinDanielson 哦,好吧,比如从它检查的数字池中删除不起作用的除数?
-
是的。 144/2 是 72,但您需要检查 144/72 吗?在某些时候,您将不再找到新号码。最简单的阈值是 n/2,这会将迭代次数减少一半。但你可以做得更好。
标签: java primes perfect-numbers