Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <time.h>
- double timeTaken(int start, int end) {
- return ((end - start) / CLOCKS_PER_SEC);
- }
- // O(n^2)
- int f1(int x) {
- int res = 0;
- int a = 1;
- for(int i = 1; i <= x; ++i) {
- res += i;
- for(int j = 1; j <= x; j++) {
- a *= 1;
- }
- }
- return res;
- }
- // O(n)
- int f2(int x) {
- int res = 0;
- for(int i = 1; i <= x; ++i) {
- res += i;
- }
- return res;
- }
- // O(1)
- int f3(int x) {
- return (int) (x * (x + 1) / 2.0);
- }
- int main(void) {
- clock_t start;
- clock_t end;
- start = clock();
- printf("f1(): %d in time: %f\n", f1(100), timeTaken(start, end));
- end = clock();
- start = clock();
- printf("f2(): %d in time: %f\n", f2(100), timeTaken(start, end));
- end = clock();
- start = clock();
- printf("f3(): %d in time: %f\n", f3(100), timeTaken(start, end));
- end = clock();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement