-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
41 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,22 +1,54 @@ | ||
package main | ||
|
||
import ( | ||
"flag" | ||
"fmt" | ||
"os" | ||
) | ||
|
||
// Recursive function for calculating the n-th Fibonacci number | ||
func fibonacci(n int) int { | ||
if n <= 1 { | ||
return n | ||
// A function for calculating Fibonacci numbers from 0 to n | ||
func fibonacciSequence(n int) []int { | ||
sequence := make([]int, n+1) | ||
if n >= 0 { | ||
sequence[0] = 0 | ||
} | ||
return fibonacci(n-1) + fibonacci(n-2) | ||
if n >= 1 { | ||
sequence[1] = 1 | ||
} | ||
for i := 2; i <= n; i++ { | ||
sequence[i] = sequence[i-1] + sequence[i-2] | ||
} | ||
return sequence | ||
} | ||
|
||
func main() { | ||
var n int | ||
fmt.Print("Enter the number of the Fibonacci number: ") | ||
fmt.Scanln(&n) | ||
var outputFileName string | ||
|
||
// Defining flags | ||
flag.IntVar(&n, "n", 10, "The number up to which to calculate the Fibonacci sequence") | ||
flag.StringVar(&outputFileName, "o", "output.txt", "The name of the output file to record the result") | ||
flag.Parse() | ||
|
||
// Calculating the sequence | ||
sequence := fibonacciSequence(n) | ||
|
||
// Opening the file for recording | ||
file, err := os.Create(outputFileName) | ||
if err != nil { | ||
fmt.Println("Error creating the file:", err) | ||
return | ||
} | ||
defer file.Close() | ||
|
||
// Writing the sequence to a file | ||
for i, num := range sequence { | ||
_, err := file.WriteString(fmt.Sprintf("Fibonacci(%d) = %d\n", i, num)) | ||
if err != nil { | ||
fmt.Println("Error writing to the file:", err) | ||
return | ||
} | ||
} | ||
|
||
result := fibonacci(n) | ||
fmt.Printf("Fibonacci(%d) = %d\n", n, result) | ||
fmt.Printf("Fibonacci numbers up to %d are written to the %s\n file", n, outputFileName) | ||
} |