Download code

From LiteratePrograms

Jump to: navigation, search

Back to Fibonacci_numbers_(Eiffel)

Download for Windows: single file, zip

Download for UNIX: single file, zip, tar.gz, tar.bz2

Fibonacci.e

 1 class FIBONACCI
 2 
 3 create
 4     make
 5     
 6 feature
 7     fib (n: INTEGER): INTEGER
 8         require
 9             n_non_negative: n >= 0
10         do
11             inspect n
12             when 0 then Result := 0
13             when 1 then Result := 1
14             else
15                 Result := fib (n-1) + fib (n-2)
16             end     
17         end
18 
19 
20     fib_iterative (n: INTEGER): INTEGER
21         require
22             n_non_negative: n >= 0
23         local
24             prev1, prev2: INTEGER
25             i: INTEGER
26         do
27             prev1 := 0
28                     
29                 -- Ensure correct behavior for n = 0

30             if n = 0 then 
31                 Result := 0
32             else
33                 Result := 1
34             end
35                     
36             from
37                 i := 1
38             until
39                 i >= n
40             loop
41                 prev2 := prev1
42                 prev1 := Result
43                 Result := prev2 + Result
44                 i := i + 1
45             end     
46         end
47 
48 
49     make
50         local
51             i: INTEGER
52         do
53             from 
54                 i := 0
55             until
56                i > 10
57             loop
58                 io.put_integer (fib (i))
59                 io.put_new_line
60                 i := i + 1
61             end
62                     
63             from 
64                 i := 0
65             until
66                 i > 10
67             loop
68                 io.put_integer (fib_iterative (i))
69                 io.put_new_line
70                 i := i + 1
71             end
72         end
73 
74 
75 end
76 


Views
Personal tools