Uploaded by Ashis Gajula

Ashis Gajula 3345.002 HW1

advertisement
Ashis Gajula 3345.002 HW1
1)
Int numOfOnes(int n){
//base case
If(n <= 0)
Return 0;
else{
int last = n%2; //last is the last bit in the binary representation
if(last == 1) // check if the last bit is one
return 1+numOfOnes(n/2) // recursively calls function and adds 1
else
return numOfOnes(n/2)// recursively calls function with out adding
2a)
Log(X) < X
Base Log(1) < 1 because log(1) = 0
Induction hypothesis: Log(k) < k(assume true because it’s the IH)
Induction step: Log(k+1)<k+1
You can factor out the k in Log(k+1) using the addition rule
Log(k) + log(1+(1/k)) < k+1
Using our IH we can assume that
Log(k) + log(1+(k/1)) < k + log(1+(1/k)) because k is larger than log(k)
2b)
If Log a (a^b) = b,
And Log a (a) = 1
Then
b = log a (a^b)/log a (a)
then
b*log a (a) = log a (a^b)
3a)
The summation typically flows like this
1+3+5+…+(2n-1) with n terms
It can also be written backwards
(2n-1) + (2n-3)+…+1
So if we take the last number and the first number and add it
(2n-1)+1 = 2n
We can keep doing this until we converge at the center.
2n+2n+…+2n with n/2 terms
There fore
(n/2)*(2n) = n^2
3b)
Can also be written as
1^3+2^3+3^3+…+n^3 =( (n(n+1))/2)^2
Base case:n=1
1^3 = 1^2
IH. Assume formula holds for n=k
RHS : 1^3+2^3+…+k^3
LHS : (k(k+1)/2)^2
Induction step: k+1
1^3+2^3+3^3+…+k^3+(k+1)^3
By IH we below statement holds
(K(k+1)/2)^2 + (k+1)^3
With some algebra we can say
((K+1)^2 * (k+2)^2)/4 which Iis
((k+1)(k+2)/2)^2
4)least to greatest
2/N < 37 < Sqrt(N)<N<Nlog(log(N))<NlogN=Nlog(N^2)<Nlog^2(N)<N^1.5< N^2<N^2log(N) < N^3
< 2^N/2 < 2^N
5)only A is true
6a)
1)N
2)N^2
3)N^3
4)NlogN
5)2^N
6)N^4
7)
x2→x4→x6→x12→x24→x30→x31→x62
8)you can use a simple binary search algorithm to find the exact value in an ordered array
Findi(array[],i){
If array[lenth(array)/2] = i
Return lenth(array)/2
Else if(array[lenth(array)/2] > i)
Findi(array[1,lenth(array)/2]
Else
Findi(array[lenth(array)/2,length(array)]
9)you start at the bottom left (0,N)
If X is the value then you exit the loop and return
If X is less than then you move up
If X is greater than yo move right
Worst case is 2N so O(N)
10a)
O(N) worst case = 2N
Loop{find the max value in array}
Loop2{find the next highest value in array}
Return the addition of two values
10b)
O(N) worst case = 2N
Loop{find the max value in array}
Loop2{find the min value in array}
Return the subtraction of two values max-min
10c)
O(N) worst case = 2N
Loop{find the max value in array}
Loop2{find the next highest value in array}
Return the multiply the two values max*min
10d)
O(N) worst case = 2N
Loop{find the max value in array}
Loop2{find the min value in array}
Return the divide of two values max/min
Download