Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #ifndef TEST
- # define TEST 1
- #endif
- #define SQUARE(a) \
- ((a) * (a))
- unsigned long
- oddsum_On(unsigned long n)
- {
- unsigned long total = 0;
- for(unsigned long i = 1; i <= n; i += 2)
- total += i;
- return total;
- }
- unsigned long
- oddsum_O2n(unsigned long n)
- {
- unsigned long total = 0;
- for(unsigned long i = 0; i <= n; ++i)
- if(i % 2 == 1)
- total += i;
- return total;
- }
- unsigned long
- oddsum_O1(unsigned long n)
- {
- return SQUARE( (n + 1) / 2 );
- }
- int
- main(void)
- {
- #if TEST == 1
- // verify that the functions work correctly
- printf("%lu\n", oddsum_O1(111));
- printf("%lu\n", oddsum_On(111));
- printf("%lu\n", oddsum_O2n(111));
- #elif TEST == 2
- // benchmark O(1) solution
- oddsum_O1(4000000001L);
- #elif TEST == 3
- // benchmark O(n) solution
- oddsum_On(4000000001L);
- #elif TEST == 4
- // benchmark O(2n) solution
- oddsum_O2n(4000000001L);
- #endif
- // example:
- // cc odds.c -DTEST=2 && time ./a.out
- // this benchmarks the O(1) solution
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement