You are on page 1of 4

1. Write an algorithm to calculate the GCD of two given integers.

Answer:

#include <stdio.h>

// Iterative function to calculate gcd of two numbers

// using Euclid’s Algorithm (basic version)

int euclid(int a, int b)

// do until the two numbers become equal

while (a != b)

// replace larger number by its difference with the smaller number

if (a > b)

a = a - b;

else

b = b - a;

return a; // or b (since both are equal)

// main function

int main()

{
int a = 30;

int b = 50;

printf("euclid(%d, %d) = %d", a, b, euclid(a, b));

return 0;

2. Write an algorithm to merge two sorted arrays

Answer: C++ implementation:

// m - size of A

// n - size of B

// size of C array must be equal or greater than

// m + n

void merge(int m, int n, int A[], int B[], int C[]) {

int i, j, k;

i = 0;
j = 0;

k = 0;

while (i < m && j < n) {

if (A[i] <= B[j]) {

C[k] = A[i];

i++;

} else {

C[k] = B[j];

j++;

k++;

}
if (i < m) {

for (int p = i; p < m; p++) {

C[k] = A[p];

k++;

} else {

for (int p = j; p < n; p++) {

C[k] = B[p];

k++;

You might also like