'Is this a O(n)? [duplicate]
What is the time complexity for this? And what's the Big-O?
int sum = 0;
for (int i = 0; i<= 20; i+=2)
for (int j = 0; j<= i; j++)
sum+= 2i * j ;
System.out.println (sum);
System.out.ptintln(“I = ” + i + “ J = ” + j);
Solution 1:[1]
Since nothing depends on any input and the number of iterations is always fixed, this has constant-time complexity or O(1). Asymptotic runtime complexity is always a property of a function describing how the number of operations change in relation to the input size.
There is no input and the function always takes the same time to execute, hence O(1).
- Function performs the same operations regardless of its input: O(1)
- Function runs twice as long when input doubles: O(n)
- Function runs 4 times slower when input doubles: O(n²)
- Function performs more operations, but less than you would expect from N: usually O(log n)
Solution 2:[2]
Since the main loop's iterations does not increase/decrease drastically with change in input, the code is O(N).
You can give whatever limit you want to the I<=20 iterator, and the iterations will grow linearly
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Sriram Vinodh |
