Welcome to Scribd, the world's digital library. Read, publish, and share books and documents. See more
Download
Standard view
Full view
of .
Save to My Library
Look up keyword
Like this
0Activity
0 of .
Results for:
No results containing your search query
P. 1
Addition

Addition

Ratings: (0)|Views: 198 |Likes:
Published by Tamir Sen

More info:

Published by: Tamir Sen on Jun 06, 2012
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

06/06/2012

pdf

text

original

 
To compute
a
n
, for integers
a
1 and
n
0, one can use exponentiation bysquaring to derive a solution in Θ(lg
n
) time. This is an improvement over thenaive solution which runs in Θ(
n
) time.
fun
is even n = n mod 2 = 0
fun
raise to power a 0 = 1
|
raise to power a 1 = a
|
raise to power a n =
letval
sqrt = raise to power a (n div 2)
ini
is even n
then
sqrt
sqrt
else
sqrt
sqrt
a
end
Listing 1: exponentiation by squaringThe same concept can be applied to multiplication.
fun
mult a 0 = 0
|
mult a 1 = a
|
mult a b =
letval
half = mult a (b div 2)
ini
is even b
then
half + half 
else
half + half + a
end
Listing 2: computing
a
×
b
in Θ(lg
b
) iterationsBut, did you know that you can also apply the concept to compute the
n
thfibonacci number in Θ(lg
n
) time?1
 
The fibonacci sequence is defined below
0
= 0
1
= 1
2
= 1
n
=
n
1
+
n
2
Let
x
=
n
1
and
y
=
n
2
, so,
n
=
x
+
y
and
n
+1
= (
x
+
y
) +
x
= 2
x
+
y
n
+2
= (2
x
+
y
) + (
x
+
y
)= 3
x
+ 2
y
n
+3
= (3
x
+ 2
y
) + (2
x
+
y
)= 5
x
+ 3
y
n
+4
= (5
x
+ 3
y
) + (3
x
+ 2
y
)= 8
x
+ 5
y
See the pattern?
n
+
k
=
k
+2
×
x
+
k
+1
×
y
(1)You can prove the above claim easily using induction for
k
0.2
 
Using claim (1) we can derive the following definitions:
n
+
n
2
=
n
×
x
+
n
1
×
y
= (
x
+
y
)
x
+
xy
=
x
2
+ 2
xy
n
+
n
1
=
n
+1
×
x
+
n
×
y
= (2
x
+
y
)
x
+ (
x
+
y
)
y
= 2
x
2
+
xy
+
xy
+
y
2
= 2
x
2
+ 2
xy
+
y
2
n
+
n
= (
x
2
+ 2
xy
) + (2
x
2
+ 2
xy
+
y
2
)= 3
x
2
+ 4
xy
+
y
2
n
+
n
+1
= (3
x
2
+ 4
xy
+
y
2
) + (2
x
2
+ 2
xy
+
y
2
)= 5
x
2
+ 6
xy
+ 2
y
2
Now, we can compute
n
in Θ(lg
n
) time.3

You're Reading a Free Preview

Download
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->