Project Euler – 1

解决 Project Euler – 问题 1。

/**
 * Problem 1
 * Multiples of 3 and 5
 *
 * If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
 * Find the sum of all the multiples of 3 or 5 below 1000.
 */

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

#define element_t unsigned long long

/* int, int */
#define is_divisible(dividend, divisor) ((dividend) == ((dividend) / (divisor)) * (divisor))

static element_t multiple(const element_t max, const element_t num1, const element_t num2)
{
  element_t tmp_num1 = num1;
  element_t tmp_num2 = num2;

  for(element_t i = 2; num1 * i < max; i++)
    tmp_num1 += num1 * i;

  for(element_t i = 2; num2 * i < max; i++)
    /* Remove the duplicate data */
    tmp_num2 += is_divisible(num2 * i, num1) ? 0 : num2 * i;

  return tmp_num1 + tmp_num2;
}

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

  element_t max = atoll(argv[1]);
  element_t num1 = atoll(argv[2]);
  element_t num2 = atoll(argv[3]);

  printf("the sum of all the multiples of %llu or %llu below %llu: %llu.n",
    num1, num2, max, multiple(max, num1, num2));
  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