CS
205 - Programming for the Sciences
Spring 2008 - Practice Exam 2b
Answers
Problem 1
Matrix multiplication
private void multiply_Click(object sender, EventArgs e)
{
double[,] matrixA = ReadMatrix(matA);
double[,] matrixB = ReadMatrix(matB);
// declare and create a result matrix
double[,] matrixR = new double[MATRIX_SIZE, MATRIX_SIZE];
for (int i = 0; i < MATRIX_SIZE; i++)
for (int j = 0; j < MATRIX_SIZE; j++)
{
// for each element of result matrix, compute a sum
double sum = 0;
for (int k = 0; k < MATRIX_SIZE; k++)
sum = sum + matrixA[i, k] * matrixB[k, j];
// set result matrix element
matrixR[i, j] = sum;
}
// "copy" result matrix into the matResult grid of textboxes
for (int row = 0; row < MATRIX_SIZE; row++)
for (int col = 0; col < MATRIX_SIZE; col++)
matResult[row, col].Text = matrixR[row, col].ToString();
}
Problem 2
Sieve of Eratosthenes
private void calc_primes_Click(object sender, EventArgs e)
{
int upper = Convert.ToInt32(upperBound.Text);
// declare and create an array to indicate if i is a prime number
// we will ignore primes[0] and primes[1]
bool [] primes = new bool[upper];
// initialize the array elements to true starting with 2
for (int n = 2; n < upper; n++)
primes[n] = true;
// start at 2, "cross out" the multiples of prime numbers
// until the square of i is greater than or equal to upper
int i = 2;
while (i*i < upper)
{
if (primes[i]) // i is a prime
{
// "cross out" the multiples of i
// start at j at the next multiple of i (i*2)
// and increment j by i
for (int j = i * 2; j < upper; j = j + i)
primes[j] = false;
}
i++; // look at next number
}
// print only the true ones
results.Items.Add("The prime numbers less than " + upper);
for (i = 2; i < upper; i++)
if (primes[i])
results.Items.Add(i);
}
02/10/08