| Exercise 1 | Exercise 2 | Exercise 3 | Exercise 4 | Exercise 5 | |
| Solution 1 | Solution 2 | Solution 3 | Solution 4 | Solution 5 | |
| Show all | Hide all | |||||
Click on the links above
Exercise 1
Write a function that takes two positive integer arguments a,b and returns the floating-point value f(a,b) = (a2+b2)/(ab-1).
Write a main() function that reads a bound B from the user and computes f(a,b) for 1 <= a < b <= B. If f(a,b) happens to be an integer, the main() function prints the value of that integer along with the corresponding values of a and b.
Solution 1
#include <stdio.h> #include <stdlib.h> double f ( unsigned long int a , unsigned long int b ) { if (a*b <= 1) return 0; return ((double)(a*a + b*b) / (double)(a*b - 1)); } int main () { unsigned long int a, b, B, t; double fab; printf("Enter a bound: "); scanf("%lu", &B); for (a = 1; a <= B; ++a) { for (b = a+1; b <= B; ++b) { fab = f(a,b); t = (unsigned long int)fab; if (fab == t) printf("f(%lu,%lu) = %lu\n", a, b, t); } } exit(0); }Exercise 2
Write a function that computes the gcd of two integers.
Write another function that uses the above function for computing the lcm of two integers.
Solution 2
int gcd ( int a , int b ) { int r; if ((a == 0) && (b == 0)) return 0; if (a < 0) a = -a; if (b < 0) b = -b; while (b > 0) { r = a % b; a = b; b = r; } return a; } int lcm ( int a , int b ) { int l; if ((a == 0) && (b == 0)) return 0; l = a * b / gcd(a,b); if (l < 0) l = -l; return l; }Exercise 3
Write a function that accepts two floating point numbers x,y and a positive integer n as input. The function prints all the n-th roots of the complex number x+iy.
Solution 3
void printRoots ( double x , double y , unsigned int n ) { double r, t, s; unsigned int i; if (n == 0) return; if ((x == 0) && (y == 0)) r = t = 0; else { r = pow(x*x + y*y, 1.0/(double)(2*n)); t = atan2(y,x) / (double)n; } s = 2 * 3.1415926535 / n; for (i = 0; i < n; ++i) { printf("%d-th root: (%lf) + i(%lf)\n", i, r*cos(t+i*s), r*sin(t+i*s)); } }Exercise 4
Express the return value of the following function in terms of its input arguments.
unsigned int f ( unsigned int x , unsigned int y ) { unsigned int d, s; s = 0; while (y != 0) { d = y % 5; y /= 5; s += x * d; x *= 5; } return s; }Solution 4
xy (The function multiplies x and y in their base-5 representations).
Exercise 5
What does the following program print?
#include <stdio.h> #include <stdlib.h> int f ( int a , int b ) { a = a + b; b = a - b; a = a - b; printf("Inside function : a = %d, b = %d\n", a, b); return a; } int main () { int a, b, c; a = 56; b = 31; printf("Inside main() : a = %d, b = %d\n", a, b); c = f(a,b); printf("Inside main() : a = %d, b = %d, c = %d\n", a, b, c); a = f(a,b); printf("Inside main() : a = %d, b = %d\n", a, b); exit(0); }Solution 5
Inside main() : a = 56, b = 31 Inside function : a = 31, b = 56 Inside main() : a = 56, b = 31, c = 31 Inside function : a = 31, b = 56 Inside main() : a = 31, b = 31