Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,974 questions

51,918 answers

573 users

How to get all int array elements that are fibonacci numbers in Java

1 Answer

0 votes
import java.util.*; 

public class MyClass {
    public static List<Integer> fibonacci_numbers(Integer[] arr) { 
        Integer max = Collections.max(Arrays.asList(arr)); 

        Integer a = 0, b = 1; 
        List<Integer> fib = new ArrayList<Integer>();  
        List<Integer> arr_fib = new ArrayList<Integer>(); 
        fib.add(a); 
  
        do {
            fib.add(b); 
            int c = a + b; 
            a = b; 
            b = c; 
        } while (b <= max);
    
        for (Integer i = 0; i < arr.length; i++) { 
            if (fib.contains(arr[i])) { 
                arr_fib.add(arr[i]);  
            }
        }      
              
        return arr_fib;

    } 
    public static void main(String args[]) {
        // 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181
        Integer[] arr = {9, 1, 31, 12, 13, 3, 89, 100, 233, 4, 144, 99}; 
    
        List<Integer> result = new ArrayList<Integer>();  
        
        result = fibonacci_numbers(arr); 
       
        System.out.println(result); 
    }
}


/*
run:

[1, 13, 3, 89, 233, 144]

*/

 



answered May 24, 2019 by avibootz
edited May 24, 2019 by avibootz
...