Wednesday, December 14, 2016

C (programming language): Summation of Arithmetic Progression with Common Difference of 1

Command:

$ cat summation1.c


Result:

#include<stdio.h>
#include<stdlib.h>
int main(int argc, char* argv[]){
        if(argc!=2){
               printf("Bad argument\n");
               exit(1);
        }
        long int a=0;
        for (long int i=1; i<=atoi(argv[1]); i++){
               a+=i;
        }
        printf("%ld\n",a);
        return 0;
}


Command:

$ cat summation2.c


Result:

#include<stdio.h>
#include<stdlib.h>
int main(int argc, char* argv[]){
  if (argc != 2){
printf("Bad argument\n");
exit(1);
}
long int a = 0;
long int n = atoi(argv[1]);
a = (n*(n+1))/2;
printf("%ld\n", a);
         return 0;
}


Command:

$ gcc -o summation1 summation1.c
$ gcc -o summation2 summation2.c
$ time ./summation1 100000000


Result:

5000000050000000

real 0m3.517s
user 0m3.511s
sys 0m0.002s


Command:

$ time ./summation2 100000000


Result:

5000000050000000

real 0m0.005s
user 0m0.001s
sys 0m0.001s