Welcome to Scribd, the world's digital library. Read, publish, and share books and documents. See more
Standard view
Full view
of .
0 of .
Results for:
P. 1

Ratings: (0)|Views: 198 |Likes:

### Availability:

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
thﬁbonacci number in Θ(lg
n
) time?1

The ﬁbonacci sequence is deﬁned 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 deﬁnitions:
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