잡다한 코딩/Project Euler (Java)

(Java) Project Euler 002 - Even Fibonacci Number

Skyleester_devNurse 2023. 12. 11. 18:00
// Each new term in the Fibonacci sequence is generated by adding the previous two terms.
// By starting with 1 and 2, the first 10 terms will be:
//                  1, 2, 3, 5, 8, 13, 21, 34, 55, 89 ......
// By considering the terms in the Fibonacci sequence whose values do not exceed four million,
// find the sum of the even valued terms.

 

Question) 

-- 피보나치 수열은 이전 두 항의 합으로 구해진다.

-- 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89...

-- 400만 미만의 피보나치 수열에서 짝수로 이루어진 항의 합을 구하라.

 

public class ProjectEuler_002 {
    public static void main(String[] args) {
        fib(1, 2);                          //  1)
    }

    static int sum = 0, seq = 0;            //  2)

    static void fib(int i, int j) {
        seq = j;                            //  3)
        if (seq <= 4000000) {               //  4)
            if (j % 2 == 0) {               //  5)
                sum += j;                   //  6)
            }
            fib(j, i + j);                  //  7)
 
        } else {
            System.out.println(sum);        //  8)
        }
    }

 

1) fib 메서드 호출. 초기 값은 1과 2로 설정.

2) 합계(sum)와 현재 항(seq)의 정의

3) 현재 항에 j의 값 입력.

4) 현재 항이 400만 미만인지 확인

5) 현재 항이 짝수인지 확인

6) 현재 항이 400만 미만이면서, 짝수이면 합계에 더하기

7) fib(i, j) ➡️ fib(j, i+j)

8) 현재 항이 400만 이상이면, sum 결과를 console에 출력


** i를 합할 것인지, j를 합할 것인지 명확하게 설정해야 함.

** 계속해서 같은 메서드를 루프돌리는 것과 같기 때문에 stack over flow에 유의해야 함.