215k views
2 votes
What is the running time of the following method in terms of N (assume N > 0): public static long fun(int N) { int x = 2; for (int i=N; i>0; i--) { for (int j=i; j

1 Answer

0 votes

Final answer:

The running time of the given method is O(N^2).

Step-by-step explanation:

The running time of the given method can be calculated by analyzing the nested loop structure. The outer loop runs from N to 1, while the inner loop runs from the current value of the outer loop to 1. Therefore, the total number of iterations will be the sum of all numbers from N to 1, which can be expressed as the sum of an arithmetic progression. To calculate this sum, we can use the formula for the sum of an arithmetic progression:
S = (N/2) * (first term + last term), where N is the number of terms. In this case, the first term is N and the last term is 1. So the formula becomes:
S = (N/2) * (N + 1). The running time of the method is directly proportional to the number of iterations, which is
N(N+1)/2. Therefore, the time complexity of the method is O(N^2).

User Kanivel
by
8.9k points