How to resolve the algorithm Fibonacci sequence step by step in the Vala programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Fibonacci sequence step by step in the Vala programming language

Table of Contents

Problem Statement

The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively:

Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: support for negative     n     in the solution is optional.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Fibonacci sequence step by step in the Vala programming language

Source code in the vala programming language

int fibRec(int n){
	if (n < 2)
		return n;
	else
		return fibRec(n - 1) + fibRec(n - 2);
}

int fibIter(int n){
	if (n < 2)
		return n;
	
	int last = 0;
	int cur = 1;
	int next;
	
	for (int i = 1; i < n; ++i){
		next = last + cur;
		last = cur;
		cur = next;
	}
	
	return cur;
}

  

You may also check:How to resolve the algorithm Strong and weak primes step by step in the PureBasic programming language
You may also check:How to resolve the algorithm List comprehensions step by step in the Mathematica/Wolfram Language programming language
You may also check:How to resolve the algorithm Pythagorean triples step by step in the Scratch programming language
You may also check:How to resolve the algorithm Deconvolution/2D+ step by step in the Ursala programming language
You may also check:How to resolve the algorithm Perfect numbers step by step in the FunL programming language