Lecture 5

Writebacks 3 3 returns to writebacks 3 2 writebacks

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: E. • writeback(S, 3, 3) returns to writeback(S, 3, 2). • writeback(S, 3, 2) sends T to the screen. • writeback(S, 3, 2) returns to writeback(S, 3, 1). • writeback(S, 3, 1) sends A to the screen. • writeback(S, 3, 1) returns to writeback(S, 3, 0). • writeback(S, 3, 0) sends C to the screen. • writeback(S, 3, 0) returns to the main program. 5 4 POWER: X^n = 1 X^n = X*X^(n-1) IF n = 0 Base Case IF n > 0 Recursive Case This can be translated easily into C++. However, we can do better: X^n = 1 IF n = 0 X^n = X * square of X^(n / 2) IF n is odd X^n = square of X^(n / 2) IF n is even 6 int power(int X, int N) { if (N = = 0) return 1; else { int HalfPower = power(X, N/2); if (N % 2 = = 0) return HalfPower * HalfPower; // Even n else return X * HalfPower * Halfpower; // Odd n } } 7 fib(1) = 1 fib(2) = 2 fib(n) = fib(n-1) + fib(n-2) Base Case Base Case n>2 This is a recursion that uses TWO base cases, and it breaks down a problem into TWO simpler probl...
View Full Document

This document was uploaded on 03/31/2014 for the course CS 114 at NJIT.

Ask a homework question - tutors are online