Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
  • Loading branch information
RazerStvH authored Oct 31, 2024
1 parent 6c2a32b commit 2d97a5c
Showing 1 changed file with 41 additions and 9 deletions.
50 changes: 41 additions & 9 deletions fibonacchi-go.go
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)
}

0 comments on commit 2d97a5c

Please sign in to comment.