In the following loop is the complexity O(1) or is it O(n)?
for(int j = 0; j < Math.random() * 1000 + 1; j++)
I don't know the number of times it would run through the loop so shouldn't it be O(n)?
Join Stack Overflow to learn, share knowledge, and build your career.
In the following loop is the complexity O(1) or is it O(n)?
for(int j = 0; j < Math.random() * 1000 + 1; j++)
I don't know the number of times it would run through the loop so shouldn't it be O(n)?
Its O(1)
because n is the input. There is no input in the code
for(int j =0 ;j<(Math.random()*1000+1);j++)
Your code will run for number of iteration which is a function of 1000 , hence O(1)
Math.random()
which is what exactly O(1) means. No matter what the input is, The program takes a constant time to execute even in the worst case scenario.
– Arun Gowda
Mar 5 '19 at 18:01
Since its a random number generator, then the complexity n*1000+1 therefore O(n). If it where a static value like 1000+1 then complexity would have been O(1). Where n is the range of the possible result the function Math.Random() can output