I am trying to determine the Big-O notation of these code-snippets:
#1:
public static void printProducts (int n) {
int a = 0; // O(1)
int b = n; // O(1)
// O(n)?
while (a < b){
// O(?) This if is checked n times, but how many times is it ran?
if (a * b == n) {
System.out.println( a + "*" + b + "=" + a*b ); // O(1)
a++; // O(1)
b--; // O(1)
}
else if ( a * b > n ) {
b--; // O(1)
}
else if ( a * b < n ) {
a++; // O(1)
}
}
}
#2:
public static void printProducts2 (int n) {
int a = 1; // O(1)
int b = n; // O(1)
// O(log n)
while (a < b){
if (a * b == n) {
System.out.println( a + "*" + b + "=" + a*b ); // O(1)
a++; // O(1)
b--; // O(1)
}
else {
if ( a * b > n ) {
b = n/a; // O(log n)
}
else if ( a * b < n ) {
a++; // O(1)
}
}
}
}
I have concluded that the Big-O notation of the first code is O(n), and O(log n) for the second, but I'm uncertain if it's correct or not. Am I on the right track here?
I have tried looking at this question, before asking my own question, but I couldn't quite understand how it applies here.