Calculate alternating sum of integers up to n
This C program calculates the alternating sum of integers from 1 to n, where n is provided by the user. It checks if n is within the range of 1 to 10^15 before performing the calculation. The result is printed as a long long integer.unknown
csharp
21 days ago
331 B
1
Indexable
Never
#include<stdio.h> #include<math.h> int main() { long long int n; long long int sum=0; scanf("%lld",&n); if(n>=1 && n<=pow(10,15)){ for(int i=1;i<=n;i++) { long long int a=pow(-1,i)*i; //printf("%d\t%d\n",i,a); sum+=a; } printf("%lld\n",sum);} return 0; }
Leave a Comment