Home > Net >  function that takes a num as input if the given num is a Fibonacci num, prints the num,else print su
function that takes a num as input if the given num is a Fibonacci num, prints the num,else print su

Time:02-28

function that takes a number as input if the given number is a Fibonacci number, prints the number otherwise, print the sum of all even Fibonacci numbers less than the given number.

Input: 20 Output: 10

Input: 21 Output: 21

I tried doing this :

 int n=22;
    int arr[]=new int[n];
    arr[0]=0;
    arr[1]=1;
    int sum=0,i=0;
    while(arr[i]<=n){
        arr[i]=  (arr[i-1]   arr[i-2]);
        if(arr[i]==n) System.out.println(n);
        i  ;
        }
     for(i=0;i<arr.length;i  ){
         if(arr[i]%2==0) sum =arr[i];
     }
     System.out.println(sum);

CodePudding user response:

You want to start at index since arr[0], arr[1] are set. Also when sum you dont want to sum last element if its bigger than n.

public class Main
{
    public static void main(String[] args) {
    int n=9;
    int arr[]=new int[n];
    arr[0]=0;
    arr[1]=1;
    int sum=0,i=1;
    
    while(arr[i]<n){
        i  ;
        arr[i]= (arr[i-1]   arr[i-2]);
        if(arr[i]==n){ 
            System.out.println(n);
            return;
        }
    }
    
    for(i=0;i<arr.length;i  ){
         if(arr[i]%2==0  && arr[i]< n) sum =arr[i];
    }
     System.out.println( sum);
    }
}
  • Related