File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change 1+ // Project Euler Problem 6
2+ // Find the difference between the sum of the squares of the first n natural
3+ // numbers and the square of the sum of the first n natural numbers.
4+ //
5+ // Formula used:
6+ // Sum of squares = n(n+1)(2n+1)/6
7+ // Square of sum = (n(n+1)/2)^2
8+ //
9+ // Example:
10+ // Input : 100
11+ // Output: 25164150
12+
13+ #include <stdio.h>
14+
15+ // Function to compute sum of squares using formula
16+ long long sum_of_square (int n )
17+ {
18+ return (long long )n * (n + 1 ) * (2 * n + 1 ) / 6 ;
19+ }
20+
21+ // Function to compute square of sum using formula
22+ long long square_of_sum (int n )
23+ {
24+ long long sum = (long long )n * (n + 1 ) / 2 ;
25+ return sum * sum ;
26+ }
27+
28+ int main ()
29+ {
30+ int n ;
31+ scanf ("%d" , & n );
32+
33+ long long answer = square_of_sum (n ) - sum_of_square (n );
34+ printf ("%lld\n" , answer );
35+
36+ return 0 ;
37+ }
38+ //this calculates in o(1) ,enter the n till which u want to find. for our case (in question) its 100
You can’t perform that action at this time.
0 commit comments