so I am trying to print the prime numbers between 1 and 100, and the total prime numbers in that range. I know the total prime numbers between 1 and 100 is 25, but I can't think of how to print it out in Java. It keeps printing 71???
Thank you for your help.
public class Chap6_Homework2 {
public static void main (String [] args) {
int i;
int maxprime = 100;
boolean isPrime = true;
String foundprimenumbers = "";
for (i = 2; i <= maxprime; i++) {
isPrime = PrimeNumbers(i);
if (isPrime) {
foundprimenumbers = foundprimenumbers + i + " ";
}
}
System.out.println("Prime numbers are " + foundprimenumbers);
System.out.println("There are " + foundprimenumbers.length() + " prime numbers found.");
}
public static boolean PrimeNumbers(int foundprime) {
for (int i = 2; i <= foundprime / 2; i++) {
if (foundprime % i == 0) {
return false;
}
}
return true;
}
}
Change to
int foundprimenumbers = 0;
for (i = 2; i <= maxprime; i++) {
if (PrimeNumbers(i)) {
System.out.println(i);
foundprimenumbers++;
}
}
// System.out.println("Prime numbers are " + foundprimenumbers);
System.out.println("There are " + foundprimenumbers + " prime numbers found.");
where you print the prime number immediately and the count of primnumbers is stored in an int
variable
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.