Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1 Remainder of Dividing by Three The easiest way to find the remainder of a give

ID: 3910735 • Letter: 1

Question

1 Remainder of Dividing by Three The easiest way to find the remainder of a given integer like 235 when dividing by three is to calculate the remainder of 2 +3+5 instead. Use this idea to implement a recursive function that calculates the remainder of any given non-negative integer when dividing by three. Your function must obey the following signature: int nMOD3 (int n, int size) where array n specifies the input integer by storing each digit in one cell and size determines how many digits the input integer has. For example, nMODS (2, 3, 5, 3) is a valid function call. The remainder of n when dividing by three has to be returned by the nMOD3 function as its output.

Explanation / Answer

int nMOD3(int n[], int size) {

int remainder = 0;

int sum = 0;

if (size <= 0) {

remainder = 0;

} else if (size == 1) {

remainder = n[0] - (n[0]/3)*3;

} else {

//calculate sum

for (int i = 0; i < size; i++) {

sum += n[i];

}

size = 0;

while (sum) {

n[size++] = sum - (sum/10)*10;

sum /=10;

}

remainder = nMOD3(n, size);

}

return remainder;

}