public class Exercise {
public static void main(String[] args) {
int integer;
int num = 2;//a number to be tested for primeness
int count = 0;//count the number of prime numbers
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a number");
integer = keyboard.nextInt();
while (count <= integer) {
boolean isPrime = true;//is current number prime
//test wether number is prime
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {//if true number is not prime
isPrime = false;//set is prime to false
break;//exit the loop
}
}
if (isPrime) {
count++;
System.out.print(num);
}
num++;
}
}
}
Hi I need this program to just print the smallest factors of an integer eg If the in put is 60 give an output of 2,3,5. It does that but it also adds a lot of other ascending prime factors. Any suggestions? Thanks
Your loop condition is meant to print first 'x' prime numbers so if you enter 60 it will print first 60 prime numbers. That is 2,3,5,7,11 ...
Please modify your code like this to get desired output (just replace the entire loop)
while (num <= integer) { //Changed the condition here to
//stop when the number reached integer and not count
boolean isPrime = true;//is current number prime
//test wether number is prime
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {//if true number is not prime
isPrime = false;//set is prime to false
break;//exit the loop
}
}
if (isPrime && integer % num == 0) {// added an additional check that
// print the number only if it is prime and
// it is divides the integer with an remainder of 0
System.out.println(num);
}
num++;
}
for entering 60 you will output as
2 3 5
Note you don't need count variable any more
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.