This program asks the user for a minimum number greater than 1 and a maximum number grater than the min. It then prints out number by number what its divisible by, if its prime or composite, and if its a perfect number in this format:
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.
At the end it displays the number of prime and perfect numbers. The program works but I am wondering if there are any ways to clean up the code/make it more efficient(or if there is anything im doing wrong)
Code:
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);
}
}