Skip to content

Commit 74871c8

Browse files
committed
Add O(1) optimized solution for Project Euler Problem 6
1 parent e5dad3f commit 74871c8

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

project_euler/problem_6/o(1)sol.c

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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

0 commit comments

Comments
 (0)