COM1201 Spring 1997 Professor Fell QUIZ 3 Solution

Problem 1: ( 5 points)
a. Given the function int BB(int n), fill in the table below.
int BB(int n){
	if (n == 0) return 0;
	if (n == 1) return 1;
	if (n % 2) return 1 + BB(n / 2);
	return BB(n / 2);
}

n in Decimaln in BinaryBB(n)
2101
51012
810001
1311013
31111115

b. What does BB compute?

BB(n) counts the number of ones in the binary expansion of n.

Problem 2: Consider the following code

void main(){
	int N = 100;
	int* A = new int[N];        		//a.
	for (int i = 0; i < N; i++)     	//b.
		A[i] = RandomLong(1, 1000); 
cout << Search(A, 100, 500); //c. } int Search(int A[], int size, int key){ //d. for (int i = 0; i < size; i++) if (A[i] == key) return i; return -1; }

Explain your answers.

If we know that the values are chosen at random from 1 .. 1000, Brian Ciccolo points out that the following analysis applies:

The probability that 500 is not in A is (999/1000)100 which is approximately 0.90
The probability that 500 is in A is 1 - (999/1000)100 which is approximately 0.10
Then expected (average) number of compares is then:

  1. 90*100 + 0.10*50 = 95.

In general, size*(999/1000)size + (size/2)(1 - (999/1000)size)
sizeaverage compares
5048.78
10095.24
200181.86
300261.11
400334.04
500401.59
750552.07
1000683.85
1500917.22
20001135.20
30001574.57
40002036.56
50002516.80
100005000.23
10000050000.00
Notice that the average compares tends to size/2.

Last Updated: April 27, 1997 10:15 pm by

Harriet Fell
College of Computer Science, Northeastern University
360 Huntington Avenue #161CN,
Boston, MA 02115
Internet: fell@ccs.neu.edu
Phone: (617) 373-2198 / Fax: (617) 373-5121
The URL for this document is: http://www.ccs.neu.edu/home/fell/COM1101/QUIZ/Q3/quiz3Solution.html