Write code to match a specific Big-O-Notation

100 Views Asked by At

Our class was challenged by a professor at uni that if we were able to find a algorithm that fittingly describes the following Big-O-Notation, we'd instantly pass his class. I wanted to ask if any of you know how this could be done since I've been struggling to make it work without just simplifying it. (Could be any language, i chose c++ for my example)

O(4n · (-2 + 3n) · (n - log(n)) / n) = ?

Simplifying it often gave me either O(n^2) or O(n^3) which would be easy enough to implement but i feel like is not the goal of the challenge. I've tried directly changing each part into algorithm logic like this:

#include <iostream>
#include <cmath>

void Algorithm(int n) {
    for (int i = 1; i <= 4 * n; ++i) { // outer loop iterates 4n times
        for (int j = 1; j <= -2 + 3 * n; ++j) { // middle loop  iterates (−2+3n) times
            for (int k = 1; k <= n - log(n); ++k) { // inner loop iterates (n−log(n)) times
                // Operations are performed here
            }
        }
    }
}

int main() {
    int n = 10; // Example value for n
    Algorithm(n);
    return 0;
}

Though I'm unsure whether that is correct

1

There are 1 best solutions below

1
Dave On

Here's an easy way:

def f(n)
  1.upto(4n · (-2 + 3n) · (n - log(n)) / n) do |i|
    // any O(1) operation here
  end
end

Though if your professor really meant O() instead of Theta() then any smaller expression would do.