r/AskProgramming • u/Remarkable-Pilot143 • Feb 14 '26
My professor claims this function is O(n), and I’m certain it’s O(1). Can you settle a debate for me? The function is below
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)) >> i) + ((n & (1 << i)) >> i) + a > 1 ? 1 : 0;
cout << "a = " << a << endl;
}
return c;}
110
Upvotes
132
u/Emergency-Lunch-549 Feb 14 '26
I'm no expert, but that looks to be O(1) because the loop is not dependent on what you input
71
u/atarivcs Feb 14 '26
Have you asked your professor why he says it is O(n) ?
67
u/rickpo Feb 14 '26
When analyzing algorithmic complexity you must specify what 'n' is.
This algorithm is O(n) where n is the number of bits in an integer. And the number of bits in an integer is absolutely not constant over all architectures or compilers. This code implements an addition operation, which is absolutely a linear time operation over the size of the integer.
If you want to claim this algorithm is O(1), you must explicitly state your assumption that sizeof(int) is constant.
28
u/AShortUsernameIndeed Feb 14 '26 edited Feb 14 '26
This is a ripple-carry adder. It is O(n) in the size of the operands. That's most likely the point your professor's trying to make. Real CPUs will typically use prefix adders, which are O(log n).
(Note that in the real world, these things are implemented in logic gates that will inherently parallelize certain aspects of the algorithm, while also being subject to different constraints like fan-out limitations. Take this with a grain of salt, I'm not a hardware person and last looked at this sort of thing at uni 30 or so years ago, when prefix adders were brand new in microprocessors.)
EDIT due to confused replies: this is not a useful piece of code to run. It computes n+m (and an overflow bit). It does that in the way a certain type of logic circuit would do it in hardware. That way has linear complexity in problem size, so O(problem size), and the problem size is the bit width of the inputs.
6
u/Leverkaas2516 Feb 14 '26
Maybe your professor is thinking it's O(n) where n is the number of bits in an integer, which could vary from platform to platform.
16
u/talkingprawn Feb 14 '26
This is O(1) as far as I can see it. The loop is constant size and the complexity of the bit shifts do not change based on the contents of the integers.
It is also O(n) because O(1) is under the curve of O(n). We wouldn’t say that in practice, because that’s not in the spirit of the intent of complexity analysis. But maybe this is the trick your professor is playing, to get you to broaden your thinking? Could be.
Maybe ask your professor why they are saying this. Present yourself as saying how it looks to you and then say you want to better understand why their answer differs from yours. Don’t claim you know the answer. You’re there to learn from the professor.
The best way to continue not understanding something is to present yourself as knowing the answer already. That prevents people from sharing things with you that you might learn from. As computer scientists and engineers, we must remind ourselves of it every single day. You have an opportunity to practice it now.
4
u/cardboard_sun_tzu Feb 14 '26 edited Feb 14 '26
Ok, my first take was, ' This professor is an idiot', but I see their point. It is potentially O(n).
On any given system, the size of an int is going to probably be a fixed constant value. I have never heard of a chip architecture that allows variable sized words or dwords, but who knows.
Now, if you are looking at this as a cross platform code snippet, the size of an int could be 8 bits, 16, 32, 64, 128. or more. There are examples of real hardware in the world today that supports all these options.
For any given platform sizeof(int) is constant. For all given platforms, sizeof(int) is variable.
If your teacher is arguing the latter, they are a mouth drooling goon, because you don't teach basic concepts using really wierd and hightly niche examples.
So yeah, there is technically a case were this could be argued as O(n).
2 MIN LATER EDIT:
I forgot to add something. Glancing at this, it looks a lot like a hash function. You really, really want hash functions to run to run in 0(1) time, partially because they get used in a lot of places where speed is really important, and partially because of security reasons.
You might loop over a O(1) hash N times for security, but this is more of an arcitecture/design question. Any algrothim can be turned into an O(n) problem in a loop.
13
u/behusbwj Feb 14 '26
This is so unnecessarily convoluted. I truly despise professors that try to complicate computer science concepts by obfuscating problems with garbage that is designed more to distract than to challenge.
3
u/BobbieGenoWrites Feb 14 '26
I’m just in the beginning steps of learning programming, so none of this makes sense to me yet. Can someone confirm what this would even be needed for or what it could be used for? Just out of interest
5
u/mjarrett Feb 14 '26
O(1)
Doesn't matter if that for loop runs once or a billion times. If the number of times it runs is not affected by the function inputs, it's a constant time block.
6
u/ericbythebay Feb 14 '26
No need to guess, write out the proof.
2
u/TotallyManner Feb 14 '26
Since the only things that are touching i inside the loop are those bit-shift operators, which I can’t be bothered to parse, there might be something tricky there. Otherwise, you’re correct that it’s O(1)
2
u/MyTinyHappyPlace Feb 14 '26
It’s both, but O(1) is more accurate. Is your prof teaching complexity theory? Then either they should explain themselves better or teach you how to have a meaningful discussion about it with them.
Because you will not win this by arguing „random redditors are on my side“ 😊
2
u/AgencyNice4679 Feb 14 '26
It depends on what’s your input space
For all practical purposes it’s O(1)
2
u/dimonoid123 Feb 14 '26
Are you redefining type int as something of variable length? For example in Python integers can have virtually infinite number of digits, limited only by size of your RAM. If not, then O(1).
2
u/guywithknife Feb 14 '26
The loop has a constant number of iterations. You can literally unroll the loop and hardcode the steps and it would give the exact same result. That is, no matter what values you pass in, it does the same number of steps.
Therefore it’s O(1)
Simple.
2
u/cardboard_sun_tzu Feb 14 '26
After reading a lot of responses here, I am reminded why interviewing for coding jobs is emotionally taxing.
There are a lot of people who think they understand this concept, and will speak about it with presumed authority.
2
u/tornado9015 Feb 14 '26
My understanding (i could be wrong) is that big o analysis is theoretical performed before compilation. I also believe that sizeof(int) is variable between systems. And lastly if you iterate some variable number of times that function is o(n). Specifically in this case the time complexity depends on the size of int, which is a value you cannot know given the available information.
If you were presented a compiled version of this code and asked to determine the complexity i would agree it is o(1) because a compiled version would have a fixed value.
2
u/notthesharp3sttool Feb 15 '26
Typically n is the size of the input as a string. The big oh notation means how the algorithm performs as this input size goes to infinity.
Your interpretation of O(1) is that the size of the integer is always fixed so it does a constant number of loops. But then the big oh notation doesn't even make sense as the input size can't grow indefinitely. The prof is saying that you should consider what happens when you use larger and larger integer types (you would need to change the implementation to use a byte array as there will not be integer types that large on your machine).
For example when people specify multiplication algorithm efficiency the n refers to the number of digits in the numbers, not the size of the numbers themselves.
2
u/Bulbousonions13 Feb 15 '26
Since the loop is not dependent on a or c, but rather a constant ... it is O(1)
2
u/csman11 Feb 15 '26
Ok, a lot of people are trying to defend the professor with “maybe he’s talking about the number of bits here.”
Well…
If the professor is secretly talking about “n = number of bits,” then he’s being the ultimate douche bag unless he is explicitly saying that, because the code is plainly written for fixed-width
intand it doesn’t scale with the value of the function parameternat all.Read that again, slowly, for the folks in the back who see the word “for” and immediately start chanting “O(n)” like it’s a summoning ritual.
The loop bound is:
That is not “n.” That is not “the value of the parameter n.” That is not “the numeric value of m or n.” That is “how wide an int is on this machine.”
So unless the professor started the explanation with something like:
“By n I mean the bit-width of the integer type / the size of the input in bits / the word size w”
…then no, we’re not doing the galaxy-brain reinterpretation where we pretend the code is about arbitrary-precision integers and “n” is the length of the number in bits. That’s not “being clever,” that’s just rewriting the question so the professor can’t be wrong.
And honestly, given what OP said, it’s way more likely the professor did the classic cargo-cult complexity analysis:
“There’s a for loop, therefore it’s O(n).”
Which is a thing people say when they remember one slide from intro to algorithms. It happens.
Now, could a professor be intentionally using “n” to mean “input size in bits” while also ignoring the fact that the code literally hardcodes the number of iterations as the bit-width of
int? Sure. Could he also be doing it on purpose as a lesson about “input size vs numeric value”? Sure. But if that’s the move, he needs to actually say it out loud, because otherwise it’s indistinguishable from being confused. And in this case, given there is literally a function parameter called “n” in the very code we’ve all seen, I think it’s clear which case it is.And to be clear: I’m not even saying he’s evil. I’m saying the evidence we have is that he wasn’t precise, and the most common explanation for that is that he’s just… wrong. Or at least sloppy.
If we want to find out which one it is, the sure way is to ask him about this loop (assume n < 64 so nobody pretends this is about UB):
Now we still have a for loop. Still one loop. Still “looks linear” to anyone doing the toddler version of complexity analysis. But this one is not linear in n. It’s exponential in n.
If he says “O(n)” again, we have our answer.
If he immediately says “O(2n)” and then clarifies that his “n” in the original discussion was “number of bits / input size,” then cool, he’s being precise and the debate changes. He’s still an asshole for not being precise to start. I would forgive him.
But until that clarification exists, calling the fixed-width
intversion “O(n)” (where n is literally a function parameter that doesn’t affect the loop bound) is just… not correct.Again here are the options:
intas written: O(1) with respect to the function inputs. Professor says O(n) because he’s confused.Both are possible explanations. But if you mean the second one, you don’t get to wink and imply it. You have to actually say it. Otherwise you’re not being helpful and galaxy-brain-professor-smart. You’re just being a smart ass.
2
u/Scf37 Feb 15 '26
Algorithm implemented is binary addition which is O(n) by book (n is bitness). It is like sorting an array of fixed length - fixing the length does not make it O(1). Unless you are willing to stick to terminology which is fun but fruitless.
4
u/SlinkyAvenger Feb 14 '26
O(1) for normal purposes. I would assume some indirect way of looking at it is that the
inttype itself is a non-obvious input because it's arch and language dependent, therefore the function's time depends on the size of int.4
u/ummaycoc Feb 14 '26
It’s
O(n)because the “size of input” is the number of bits. In any specific C implementation the number of bits in anintwill be fixed but your professor (I imagine) is stating this more in a wider look at the computation sense not a specific C implementation sense. (I’m assuming the context is C).There are better examples to make you think like this.
1
u/esaule Feb 14 '26
First of all. A function that is O(1) is also O(n). Big Oh is an "at most" definition.
This function is exactly in Theta(sizeof(int)), the value of n does not matter.
So if you are in a theoretical context where sizeof(int) is O(1), which in most context, it is. Then this function is in O(1). Note that it is also in O(n) and in O(m) and in O(n*m) and in O(n!)
1
u/jason-reddit-public Feb 14 '26
Just unroll the loop by hand and you'll win the argument.
1
u/AwkwardBet5632 Feb 14 '26
It’s O(1) because int has a fixed size. If input was not bounded, it would be O(log N).
1
u/SufficientStudio1574 Feb 14 '26
Any algorithm is O(1) if you have a fixed input size. There's nothing interesting about that. The key is what the N is.
This algorithm is clearly O(n) with respect to the size of the input. The fact that this specific implementation fixes the input size doesn't change that.
1
u/georgesovetov Feb 14 '26
n is the number of bits in a number here. If the input is a single number, it's often assumed to be of variable length.
1
u/SnugglyCoderGuy Feb 14 '26
It is constant time since sizeof(int)*8 is a constant (i think, the * 8 notation is weird to ne, but 8 is constant)
1
u/bestjakeisbest Feb 14 '26
f should be constant time or O(1) the loop will always run the same number of times no matter how the inputs to the function change. like there isnt a lot to argue here, your teacher is either missing something or is assuming something else, like if you were turning this algorithm into something that could work for arbitrarily large numbers then it would be O(log(n)+log(m)) but this function is not implemented as such.
1
u/aq1018 Feb 14 '26
The algorithm is O(n), but the implementation is technically O(1)… implementation is essentially hardcoded to 32 bits. But the algorithm itself is dependent on input size in bits?
1
u/Wooden-Engineer-8098 Feb 14 '26
actually this question is silly. n is the length of an input. this function doesn't support inputs of different length at all. so what is the n?
1
u/wbrd Feb 14 '26
Run it 10000 times with MAXINT as the inputs and then 0 as the inputs and compare the times.
Also, name your functions and variables properly.
1
u/tom-md Feb 14 '26
Arguing isn't going to progress the conversation. Benchmark it on all 232 input values and show how it performs the same regardless of your input value.
1
u/smooth_metal57 Feb 14 '26
Since I personally get hives from bit-twiddling, I recommend you quit school and become a florist.
1
u/Kazyne Feb 14 '26
It is O(n) with n = the number of bits you are adding
1
u/regular_lamp Feb 15 '26 edited Feb 15 '26
This is probably more a disagreement about what N is in this case. And maybe some pedantry about how
sizeof(int)isn't necessarily the specific size you expect. Imagine this was a template written usingsizeof(T)then it would be reasonable to point out that it is linear in the size of T...Edit: also If I felt pedantic I'd point out that the use of buffered iostreams inside the loop makes the actual "runtime" of this wildly unpredictable. For all you know you are flushing megabytes of buffered stuff in that line.
1
u/beingsubmitted Feb 15 '26
It's O(1) unless you treat bit width or the size of int as n. Perhaps that's what you're professor is thinking, or the justification they'll eventually provide. The reason that's a bad justification, though, is that if treating the bit width as n counted, then practically every algorithm becomes O(n) at a minimum. Hash table lookups? O(1) relative to the size of the hash table, but O(n) relative to the bit width.
1
u/White_C4 Feb 15 '26 edited Feb 15 '26
You're not wrong that it's O(1) because the loop size is known from compile time, so no matter how many times you rerun the program, it's always guaranteed to be the same size.
If I write code like this:
It's no different than just doing this:
The distinction in O(1) and O(n) is the definition of the value "n". But we typically equate n to be an arbitrary size that cannot be figured out during compile time.
1
u/schungx Feb 15 '26
I once heard a tutor describe it this way:
O(1) = some sane number
O(n) = a godzillion if n is a godzillion
O(n2) = a mind boggling large number
Essentially set n to a very large godzillion number and things will clarify.
1
u/[deleted] Feb 15 '26
It depends on whether the operation n & (1 << i) is O(n) or O(1). The for loop doesn’t add to its time complexity.
1
u/carolus_m Feb 15 '26
Note that if you are right then so is your teacher since O(1) implies O(n)
1
u/No_Cook_2493 Feb 15 '26
It's O(n) because it's a loop obviously! /s
1
u/EternalStudent07 Feb 15 '26
That's not the clearest situation to read an O notation for. I don't understand why those steps are happening. What the data set size is.
O(n) is not m or n in your function declaration. It's the number of elements your code would act on. If it worked on half as many elements, would the total work change.
Normally the for loop would be acting on all the elements of the data set once. That'd leave you with O(n), where total work is proportional to how much you change the set size.
It almost looks like you parameterized the data set creation, or tried to. Again, I don't follow what the m or n are doing here. Sorry I rarely use bitwise operators or shifts lately.
And I assume you're claiming the function is O(1) because any valid numbers you call it with (m and n) should cause the same amount of work. It'll output different values for different inputs, but it'll output 8 times (I believe) per f(...) call. Or some set number that only changes if the size of an int changes.
Most things can differ depending on your perspective, so problem descriptions matter too.
1
u/MikeWise1618 Feb 15 '26 edited Feb 15 '26
Sadly there are a lot of professors like that.
However if something is O(n) then for any amount of time, there is an input that will get you there(theoretically). Ask how you can get that function to take a minute.
1
u/StormyDLoA Feb 15 '26
It's technically O(n) for the size of int, but O(1) in m or n.
1
u/RazorBest Feb 15 '26
O(1) <= O(n). You are right, but technically, so is your your teacher. Similarly, the function is also O(en).
1
u/drraug Feb 15 '26
run and benchmark
1
u/an-la Feb 15 '26 edited Feb 15 '26
If this is c++, the code as written will not compile.
m and n are undefined I'm assuming \* is a formatting typo.
but... sizeof(int)*8 would be a compiletime constant (32 most likely)
O(32) = O(1)
So constant time, though you could achieve the same result through a simple macro expansion and avoid the performance cost of a loop.
given that we do not know m and n, and the purpose of the algorithm correctness is an open question
edit: a good optimizing compiler would probably expand the constant loop
1
u/FitMatch7966 Feb 15 '26
The algorithm is O(n) where n is the number of bits in the bitfield. In this case, the bitfields are fixed at the int size (32 or 64 usually), making the implementation O(1) for any given machine. Extrapolate this to an arbitrary size bitfield and it is O(n)
1
u/ziggybeans Feb 15 '26
Former Instructor of Software Engineering here. This is a bullshit trick question. If I put this in an exam, I would be looking for my students to question what variable Big-Oh is a function of.
Generally speaking, people use Big-Oh as a function of the size of the inputs. In this case, your inputs are the two integer variables, m and n. Their size does not change the way an array or list does — there are always only two input values. So it’s not that…
Your argument for O(1) is solid and any reasonable programmer would come to that conclusion. The function takes the same number of actions no matter what its input values are.
BUT — and maybe this is where your professor is coming from — what if you consider Big-Oh as a function of the size of an integer?
That loop is going to run 1 iteration on an 8-bit microcontroller; 2 iterations on a 16-bit microcontroller; 4 iterations on a 32-bit architecture; and generally N/8 iterations on an N-bit machine. Thus, O(N) where N = the size of an integer values.
Now again - that would make this a bullshit trick question - but as a professor, my expectation is that your answer demonstrates deep understanding of Big-Oh, not just that you can count loop iterations. Your professor may be arguing O(n) just to push you to think outside of a box, and to elaborate on or justify your answer.
1
u/cormack_gv Feb 15 '26
Under the unit cost model, sizeof(int) is O(1), as are all operations on ints. So the overall running time is O(1)*O(1) = O(1).
1
u/KingAggressive1498 Feb 15 '26
the function is undeniably O(1), but that's because it is a specialization of an algorithm that is O(n) for a constant n.
Most people will never actually use this algorithm in production code. But a possible reason that one might is variable-sized integers (on real hardware there's significantly better approaches though, so even then not that likely).
So your professor is being obtuse to be instructive, giving them the benefit of the doubt at least. This is something any teacher should absolutely be willing to explain.
1
u/kiner_shah Feb 16 '26
What does this function do? What's a, b, c, d, etc.?
1
u/anarchalien Feb 16 '26
Dreadful readability
1
u/nimrag_is_coming Feb 16 '26
Wow dude that function is utterly incomprehensible, using slightly longer variable names doesn't degrade performance.
And yeah it's probably O(1) since it doesn't seem to do any looping depending on n
1
u/No-Initiative7768 Feb 17 '26
you are not limited to one char by variable name.
1
u/SirMarkMorningStar Feb 17 '26
While this exact code is O(1) for the reasons everyone else is states, the theoretical generic version of the algorithm is O(n) because sizeof(int) generically should be the max size of the the two integers. Imagine they were passed in as binary 0s and 1s of unlimited length.
Wait! They are O(n) if n is the number of digits, but the number of digits isn’t linear to the size of the number. 100/3 ≠ 1000/4, for example. O(log(n)), where n is the max number?
1
u/m235917b Feb 17 '26
In theoretical computer science, it is typically not assumed, that Integers have an upper limit and thus, we ignore the fact that any integer has (typically) 4 byte size. So, in general, those arithmetic operations that happen inside of the loop (not the loop itself) would be O(log(max{n,m})). And i guess the professor simplified this to O(n) even though that would technically also be wrong.
The thing is, the big O notation doesn't make sense if you consider the limitations and specifications of a specific machine. Because in that case almost every algorithm that doesn't depend on user Input or has an endless loop runs in a constant amount of time. However, even then it would be false to say O(1), since it doesn't matter if the input size is limited. What matters is "how long does the algorithm run depending on the input size?". And in fact, for bigger numbers, addition and the bit operations take longer theoretically. But not O(n), since the Integers are binary encoded. So it's O(log(max{n,m}).
That is why it is almost always assumed that you could theoretically even input something like 1010^100 or so, even though an integer cannot be that large on a real computer.
Now, the thing is, you are still not wrong though. Because real computers always add entire integers in one op. So, even though in any algorithmics paper they would say O(log(max{n,m}), your answer is still the correct one for the specific C implementation on most modern computers. But, as I said, even though that is correct, it is not the point of the big O notation and using it like that makes it useless, as almost any algorithm becomes constant.
1
u/ExcellentMaize7008 Feb 17 '26
Depends what function explicitly being talked about.
for (int i = 0; i < sizeof(int)*8; i++) <- This is O(1), as the complexity is constant, as it's sizeof(int) * 8 = 32 (where's the \ come into it? it's either divide or multiply not both, although it might just be an escape char so I'll ignore divide, either way - constant complexity)
The source of confusion could lie with the function parameter 'int n'.
I've had some real insufferable lecturers and professors during undergrad & postgrad. If possible, I'd try to change the variable names so it's not possible to see the variable 'n' as O(n). Trust me, try to rework it to be less obfuscated and easier to explain :)
1
u/MinuteScientist7254 Feb 18 '26
Constant time.
1
u/CoachBigSammich Feb 14 '26
Perplexity says O(1), so I say it's O(1)
1
u/weeeezzll Feb 14 '26
Can't you just test it with a range of values to prove this?
-1
u/TheMrCurious Feb 14 '26
Why are you certain it is O(1)?
0
u/KaleidoscopePlusPlus Feb 14 '26
the fuck am i looking at