‹ Back to the paper
Consider the following snippet, calculate the time complexity assuming the code compiles…
Consider the following snippet, calculate the time complexity assuming the code compiles successfully.
double m = 1, n = 1;
for (int i = 0; i < x; i++)
{
m *= Math.random( );
}
for (int j = 0; j < y; j++)
{
n *= Math.random( );
}Answer
Answer
AI$O(x + y)$, which is linear time complexity, $O(n)$: the two for loops run one after another (not nested), taking $x$ and $y$ steps respectively, so the total number of steps grows linearly with the input sizes.
From ISC Computer Science - Competency Focused Practice Questions (CISCE, August 2024), question 40.