exercise

3.1 Asymptotic growth

a) and The statement is proved

If then meaning that In this case Te statement is disproved

b) The statement is proved

Note that: The statement is proved

We can show that So The statement is proved

3.2 substring counting

a) naive algorithm

has_k_ones(string s)
	int cnt = 0
	for i=0 to s.length-1
 if s[i]=='1' then cnt++
	if cnt==k then return true
	else return false
int cnt=0
for i=0 to n-k
	for j=i+k to n
 if has_k_ones(s[i:j])
 cnt++

We need time to iterate through every possible substring of , and for each substring we need time to check if it has ones (using the function has_k_ones). Thus, we need time to solve the problem

b)

t[0...n]
int j=0
for i=0 to n-1
	if s[i]==1
 j++
	t[j]++

the pseudocode contains a single loop that iterate through the string. Thus the runtime is

c)

cnt=0
for l=0 to k
	cnt+=suffix[l]*prefix[k-l]

If there is l ones in the suffix of , there should be k-l ones in the prefix of . And the pseudocode adds up all the possible combinations of suffix of and prefix of .

This step costs k operations. Since when the solution of the problem is trivial, we always have . Thus this step costs

d)

spanning(m,k,s)
	suffix[]=calcualte_suffix()
	prefix[]=calcualte_prefix()
	cnt=0
	for l=0 to k
 cnt+=min(suffix[l],prefix[k-l])
	
	leftstring=s[0:m]
	rightstring=s[m+1:s.length]
	
	cnt+=spanning(leftstring.length/2,k,leftstring)
	cnt+=spanning(rightstring.length/2,k,rightstring)
	return cnt

3.3 Counting function calls in loops

a)

b)

Another method

Proof:

3.4

a)

int f[n]
f[0]=0
f[1]=1
for i=2 to n
	f[i]=f[i-1]+f[i-2]

The algorithm costs The algorithm contains a single loop that iterate from 2 to n. Within each iteration only one addition operation will be operated.

Optimize the storage ( memory)

f0=0
f1=1
for i=2 to n
	f0,f1=f1,f0+f1
return f1

b)

int f[]
int i=0
while f[i]<k do
	f[i+1]=f[i]+f[i-1]
	i++

The algorithm continues to calculate the next Fibonacci number until it reaches , so that we know f[i] is the answer when the program ends.

Using the bound proved in Exercise 2.2 , we know so we can find the answer as long as assume n is the smallest n Therefore, there exists such that Hence

3.5

a)

b)

power(a,n)
	if(n==1)return a
	int ans=power(a,n/2)
	return ans*ans

c) times of integer multiplications

d) IH: for all of the form for some Base: (shown by the line 2) IS: (shown by the line 3 and 4)

e)

int power(int a, int n) {
 if (n == 0) return 1;
 int ans = power(a, n / 2);
 ans *= ans;
 if (n & 1) ans *= a;
 return ans;
}

OR

int power(int a,int n){
	return n?power(a*a,n/2)*(n&1?a:1):1;
}