【问题标题】:Calculate big O notation for prime numbers计算素数的大 O 表示法
【发布时间】: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),因为这是算法中最大的循环。

【问题讨论】:

    标签: java big-o


    【解决方案1】:

    对于循环的每一轮,您使用 isPrime 函数检查数字是否为素数,即 O(n)。对每一轮都这样做会使你的整体复杂度 O(n^2)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-23
      • 2022-07-18
      • 2020-05-01
      • 1970-01-01
      • 2013-11-25
      相关资源
      最近更新 更多