Is this function O(n) or O(1)?

February 13, 2026 5 answers
Asked by front2station
I have a debate going on with my professor about the time complexity of a function I've written. The code is as follows: ```cpp int f(int m, int n) { int a = 0, c = 0; for (int i = 0; i < sizeof(int)*8; i++) { c += ((m & (1 << i)) + (n & (1 << i)) + (a << i)) & (1 << i); a = ((m & (1 <> i) + ((n & (1 <> i) + a > 1 ? 1 : 0; cout << "a = " << a << endl; } return c; } ``` My professor insists the function is O(n), but I believe it's O(1) since the loop's operations don't seem to depend on the input size. Can anyone help clarify this?

Answers

route-via-tunnel
Iโ€™m still learning programming and this is all pretty confusing. Can anyone explain the purpose of analyzing function complexity? What does it actually mean in practical use?

marathon.pacer: Great question! Complexity analysis helps you predict how code behaves with different inputs, essentially ensuring you know how it will perform as data size increases. It's like assessing performance for better code optimization.

Reply to this answer
9holeCourse
For sure, it's O(1)! The number of operations here really doesn't change based on m or n. It's more about how the operations scale with input size. Tell your professor this! But also, it might help to ask him for his reasoning so you can understand his perspective better.

calm..and..collected: Absolutely! Opening a dialogue could clarify things and help you both come to a better understanding.

Reply to this answer
!26 oranges peeled
It's both O(1) and O(n) in theory. Any O(1) function is also considered O(n) because it doesn't exceed that rate. However, practically speaking, it's more accurate to call it O(1) since it doesn't vary with the size of your integers.

bus__stop shelter: That's a great way to look at it! It's nice to know that while we can categorize it technically as O(n), O(1) describes its actual behavior better.

Reply to this answer
~waiting on results
I think it's O(1). The loop iterates based on the number of bits in an integer (which is constant), not the actual values of m or n. If it doesn't change with input size, it usually qualifies as O(1). Maybe your professor is looking at a broader context where he sees input size as the number of bits.

Hacksaw: That makes sense! The loop size being constant points to it being O(1) in practical terms while technically fitting into O(n) depending on the input size. It's tricky!

Reply to this answer
drama club 91
Honestly, I see it as O(1). The loop count is constant due to the fixed size of an int, and I think discussing this with your professor could help you both figure it out. Show some eagerness to learn and you might get some valuable insight.

textile+care: Yes! Engaging him might just clear up any confusion and give you better insights!

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions