From 74871c85e95fe22707d0b34c4bf8bf5791f65cbd Mon Sep 17 00:00:00 2001 From: Krishna Date: Tue, 16 Sep 2025 19:50:10 +0530 Subject: [PATCH] Add O(1) optimized solution for Project Euler Problem 6 --- project_euler/problem_6/o(1)sol.c | 38 +++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 project_euler/problem_6/o(1)sol.c diff --git a/project_euler/problem_6/o(1)sol.c b/project_euler/problem_6/o(1)sol.c new file mode 100644 index 0000000000..3847ad199a --- /dev/null +++ b/project_euler/problem_6/o(1)sol.c @@ -0,0 +1,38 @@ +// Project Euler Problem 6 +// Find the difference between the sum of the squares of the first n natural +// numbers and the square of the sum of the first n natural numbers. +// +// Formula used: +// Sum of squares = n(n+1)(2n+1)/6 +// Square of sum = (n(n+1)/2)^2 +// +// Example: +// Input : 100 +// Output: 25164150 + +#include + +// Function to compute sum of squares using formula +long long sum_of_square(int n) +{ + return (long long)n * (n + 1) * (2 * n + 1) / 6; +} + +// Function to compute square of sum using formula +long long square_of_sum(int n) +{ + long long sum = (long long)n * (n + 1) / 2; + return sum * sum; +} + +int main() +{ + int n; + scanf("%d", &n); + + long long answer = square_of_sum(n) - sum_of_square(n); + printf("%lld\n", answer); + + return 0; +} +//this calculates in o(1) ,enter the n till which u want to find. for our case (in question) its 100