Project Euler – 2

解决 Project Euler – 问题 2。

/**
 * Problem 2
 * Even Fibonacci numbers
 * 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.
 */

#include <stdio.h>
#include <stdlib.h>

#define element_t unsigned long

/** begin fibonacci */

// bottom-up
static element_t * fibonacci;     // NOTE: does not include indces 0
static element_t exp_len;
static element_t exp_max;

static element_t act_len = 1;

static void init_fibonacci(element_t n)
{
  exp_max = exp_len = n;
  fibonacci = malloc(sizeof(element_t) * (exp_len + 1));

  for (size_t i = 0; i < exp_len + 1; i++)
    fibonacci[i] = 1;
}

static void calc_fibonacci()
{
  for (size_t i = 3; fibonacci[i - 1] < exp_max; i++, act_len++)
    fibonacci[i] = fibonacci[i - 1] + fibonacci[i - 2];
}

static void free_fibonacci()
{
  free(fibonacci);
}

/** end fibonacci */

static unsigned is_even(element_t num)
{
  return num % 2 == 0;
}

int main(int argc, char const *argv[])
{
  if (argc != 2) return EXIT_FAILURE;

  int len = atoi(argv[1]);

  init_fibonacci(len);

  calc_fibonacci();

  element_t sum_fibonacci = 0;
  for(size_t i = 0; i <= act_len; i++)
    sum_fibonacci += is_even(fibonacci[i]) ? fibonacci[i] : 0;

  printf("the sum of the even-valued terms(%lu): %lun", exp_max, sum_fibonacci);

  free_fibonacci();

  return EXIT_SUCCESS;
}

作者: YanWen

Web 开发者

发表评论

Fill in your details below or click an icon to log in:

WordPress.com 徽标

You are commenting using your WordPress.com account. Log Out /  更改 )

Google photo

You are commenting using your Google account. Log Out /  更改 )

Twitter picture

You are commenting using your Twitter account. Log Out /  更改 )

Facebook photo

You are commenting using your Facebook account. Log Out /  更改 )

Connecting to %s