【发布时间】:2021-03-04 16:37:37
【问题描述】:
import java.util.Scanner;
/**
Prints all prime numbers less than a given value
*/
public class PrimeNumberMethod {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a value for n: ");
int n = input.nextInt();
System.out.println("The prime numbers in the first " + n +
" numbers are ");
printPrimeNumbers(n);
}
public static void printPrimeNumbers(int n) {
final int NUMBER_OF_PRIMES_PER_LINE = 10; // Display 10 per line
int count = 0; // Count the number of prime numbers
int number = 2; // A number to be tested for primeness
int runcount = 0;
// Repeatedly find prime numbers
while (number < n) {
runcount++;
if (isPrime(number)) {
count++; // Increase the count
if (count % NUMBER_OF_PRIMES_PER_LINE == 0) {
// Print the number and advance to the new line
System.out.printf("%-5s\n", number);
}
else
System.out.printf("%-5s", number);
}
// Check if the next number is prime
number++;
}
System.out.println("\n"+runcount);
}
/** Check whether number is prime */
public static boolean isPrime(int number) {
for (int divisor = 2; divisor <= number / 2; divisor++) {
if (number % divisor == 0) { // If true, number is not prime
return false; // number is not a prime
}
}
return true; // number is prime
}
}
我和我的朋友一直在尝试计算大 O 符号,但我们迷路了。我们知道外循环的符号是 O(n),但内循环是什么?整个程序的大 O 表示法是什么,我们认为它是 O(n),因为这是算法中最大的循环。
【问题讨论】: