Exercise 3 (by Mikael Eriksson, TA HT2015)

-lm for linking math library. Dynamic linking unless using -static.



Info on labs: Think of the bonus dead lines as lab sessions where you are already done and just present. Not good to try to present at the end of the session. Present early, that way, if you still have bugs that you didn't find, you have time to fix them.



Implement collatz algorithm in C.



Scan through and pick from ”exercises 3”.



/*

Stuff from exercise 3,

Use at your own risk :)

/miker, 19-Nov 2015

*/


#include <stdio.h>

#include <math.h>



int collatz(int n) {


if (n % 2 == 0) {

return n/2;

} else {

return 3*n + 1;

}

}



/* IN: start value (int)

* OUT: nothing

* DEPENDENCIES: none

* EFFECTS: prints the collatz sequence from start value

*/

void print_collatz_sequence(int start) {

while (start != 1) {

printf("%d\n", start);

start = collatz(start);

}

printf("1\n");

}


int sum1(int n) {

int sum = 0;

int i;

for (i = 1; i <= n; i++) {

sum += i;

}

return sum;

}


int sum2(int n) {

int sum = 0;

int i = 1;

while (i <= n) {

sum += i;

// i += 1;

i++;

}

return sum;

}


int sum3(int n) {

return n*(1 + n)/2;

}


void ex_3_3_1() {

int i;

for (i = 1; i <= 10 ; i += 3) {

//if (i < 5 && i != 2) {

printf("X");

// }

}

}


void ex_3_3_3() {

long m = 1100;

do {

printf("%ld\n", m);

m = m + 100;

} while(m < 1000);


return;

// long m;

printf("%ld\n", m);

for (m = 100; m < 1000; m += 100) {

printf("%ld\n", m);

}

}


void log2test(n) {

int i;

int l = 0;

for (i=1; i<n; i = i*2) {

l++;

}

printf("n: %d, l: %d\n", n, l);

}


double func(double x) {

return sqrt(x*x + 1);

}


double integral(double a, double b, int n) {

/* Interesting observation: the calculated dx is

rounded so that the terms do not sum up to the interval

exactly. In some cases below a whole term is missed

because of this!

Exercise: How could you correct the loop to make it safe?

*/

double sum = 0;

double dx = (b - a) / n;

double x;

for (x = a; x <= b; x += dx) {

sum += func(x);

}

printf("%16.16f", x);

sum -= 0.5 * (func(a) + func(b));


return dx * sum;

}


main() {

int n;

for (n = 10; n < 100000; n = 4*n) {

printf("%10d %.10f\n", n, integral(0, 1, n));

}

return;

int x = 7;

for (x = 100; x < 100000; x += 500) {

log2test(x);

}

return;

printf("%d\n", x);

// print_collatz_sequence(x);

ex_3_3_3();

return;

printf("%d\n", sum1(3));

printf("%d\n", sum2(3));

printf("%d\n", sum3(3));

}