In the following program fragment, , , and TwoLog_n are integer variables, and is an array of integers. The variable is initialized to an integer , and TwoLog_n is initialized to the value of
for (k = 3; k <= n; k++)
A[k] = 0;
for (k = 2; k <= TwoLog_n; k++)
for (j = k+1; j <= n; j++)
A[j] = A[j] || (j%k);
for (j = 3; j <= n; j++)
if (!A[j]) printf("%d", j);
The set of numbers printed by this program fragment is
View worked solution
Answer: D
To find the set of numbers printed by the program, let us analyze the conditions under which a number is printed.
- Initialization: The array elements are initialized to for all .
- Update Rule: The nested loops update as: for all such that . This means becomes if there is at least one in the range that does not divide .
- Condition for Printing: For to be printed, we must have at the end, which requires to be divisible by all integers in the range .
Let us analyze the two possible cases for any :
- Case 1:
Here, must be divisible by . For any , can never be divisible by (since ). Thus, will always become . - Case 2:
Here, must be divisible by all integers from up to . This means must be a multiple of the Least Common Multiple: Since grows exponentially, for all . Because , no such multiple can exist in the range .
Since becomes for every , the condition !A[j] is never met, and no numbers are printed. The printed set is empty, .
Free practice · Your answers on this page are not saved.
