Sum of squares and peace parties

Source: Internet
Author: User
Tags pow
sum of squares and peace parties Problem Description:

The sum of squares of the first 10 natural numbers is 12+22+32+...+102=385, the first 10 natural numbers and the square is (1+2+3+...+10) 2=552=3025;

The difference between the sum of squares and the sum of squares is 3025-385=2640. Now given an n, ask you to find the sum of the squares of the first n natural numbers and the difference between the peace and the square.

Input:

An integer n

Output:

An integer (the sum of the squares of the first n natural numbers and the difference between the peace Parties)

For example

Input:

10

Output:

2640 Solution One:

The first and the most stupid solution, that is, directly to the problem of the calculation process simulation to obtain,,, the final direct output result

The C language code is as follows:

#include <stdio.h>
#include <math.h>
void Main ()
{
    __int64 result,sum1=0,sum2=0;	
    int n,i;	
    scanf ("%d", &n);	
    for (i=1;i<=n;i++)		
    {		
        sum1+=pow (i,2);		
        sum2+=i;		
    }	
    Sum2=pow (sum2,2);	
    RESULT=SUM2-SUM1;
    printf ("%i64d\n", result);
}


Solution Two:

First of all, let's write down the two formulas in the question first.



The Final Solution is:

The C language code is as follows:

#include <stdio.h>
void Main ()
{
	__int64 result=0;
	int n,i,j;
	scanf ("%d", &n);
	for (i=1;i<n;i++)
	{
		result+=2*i* (((n-i) * (i+1+n))/2);
	}
	printf ("%i64d\n", result);
}
Solution Three:

This formula is proved by mathematical inductive method



The C language code is as follows:

#include <stdio.h>
#include <math.h>
void Main ()
{
	__int64 result,n,sum1,sum2;
	scanf ("%i64d", &n);
	Sum1= (n (n+1) * (2*n+1))/6;
	Sum2=pow (n (n+1))/2,2);
	RESULT=SUM2-SUM1;
	printf ("%i64d\n", result);
}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.