Project Euler – 6

解决 Project Euler – 问题 6。

/**
 * Problem 6
 * Sum square difference
 *
 * The sum of the squares of the first ten natural numbers is,
 *                                                12 + 22 + ... + 102 = 385
 * The square of the sum of the first ten natural numbers is,
 *                                            (1 + 2 + ... + 10)2 = 552 = 3025
 * Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
 * Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
 */

#include <stdio.h>

#include <stdlib.h>
#include <math.h>

#define element_t unsigned long long

static element_t sum_squares(const element_t end)
{
  element_t result = 0;
  for (element_t i = 1; i <= end; i++)
    result += (element_t)pow((double)i, 2.0);
  return result;
}

static element_t square_sum(const element_t end)
{
  element_t result = 0;
  for (element_t i = 1; i <= end; i++)
    result += i;
  return (element_t)pow((double)result, 2.0);
}

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

  printf("the difference between the sum of the squares of the first %llu natural numbers and the square of the sum is %llu.n",
    end, square_sum(end) - sum_squares(end));

  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