Fibonacci Series – Salesforce

There might a lot of resources out in the web to determine if a string is palindrome using Javasript, C#, Java and other programming languages. I took a step-back and thought of sharing the code in Apex to help.

Approach – 1: Visualforce Page + Apex

Visualforce Page

<apex:page controller="FibonacciController" docType="html-5.0">
    <apex:form>
        <apex:inputText value="{!fibSeqNm}" label="Enter input" />
        <apex:commandButton value="Generate Fibonacci Sequence" action="{!generateFibSequence}" />
        <div style="font-weight: 25px;">{!fibSeqStr}</div>
    </apex:form>
</apex:page>

Apex controller

public with sharing class FibonacciController {
    
    // Input VF variable to get the text
    // from user
    public Integer fibSeqNm {get;set;}
    
    // Output VF variable to show the result
    public String fibSeqStr {get;set;}
    
    public PageReference generateFibSequence() {
        Integer n1 = 0;
        Integer n2 = 1; 
        Integer next_num;
        List<Integer> initialLst = new List<Integer>{0}; // the inital array, we need something to sum at the very beginning
        for ( Integer i = 1; i <= fibSeqNm; i++) {
            next_num = n1 + n2; // sum of n1 and n2 into the next_num  
            
            n1 = n2; // assign the n2 value into n2  
            n2 = next_num; // assign the next_num into n2  
            initialLst.add(n1);
        }
        fibSeqStr = String.join(initialLst, ',');  // displaying the numbers in string sequence as output
        return null;
        
    }
        
}

Approach – 2: Visualforce Page + JS

<apex:page controller="FibonacciController" docType="html-5.0">
    <script>
    	function generateFibonacci() {
            let inputStr = document.getElementById('fibSeqNm').value;
            let number1 = 0, number2 = 1, nextNumber, i;
            let numberArr = [0];
            
            for(i = 0; i <= inputStr; i++ ) {
                nextNumber = number1 + number2;
                number1 = number2;
                number2 = nextNumber;
                numberArr.push(nextNumber);
            }
            
            document.getElementById('fibSeqStr').innerHTML = numberArr.toString();
        }
    </script>
    <input type="text" id="fibSeqNm" value="" />
    <button onclick="generateFibonacci()">Generate Fibonacci Sequence</button>
    <div id="fibSeqStr" style="font-weight: 25px;"></div>
</apex:page>