Lab 04 - Test Cases
Thanks for my Lab Tutor Zhang Puyu
Slides:
Testing
Some conventions
It is impossible to enumerate all test cases.
It is possible to divide the test cases into a few groups.
We can choose to test for all possible classes of inputs/outputs.
Test for the boundary cases according to the constraints given.
Test Case Design
Should cover all conditional (i.e. for all conditional branch, there exists at least one test case which can enter that branch)
Should contain at least one case for 0 iteration and at least one case for k iterations where .
Should contain boundary conditions.
Example
Design the test cases for the program below:
long find_least_significant_9(long n) {
long count = 1;
while (n != 0) {
if ((n % 10) == 9) {
return count;
}
n /= 10;
count += 1;
}
return 0;
}
We won't enter the loop
while n != 0
, that means and now our output is 0, which is correct.We enter the loop, which means .
We don't enter the conditonal first. So, that means there is no 9 in
n
We enter the conditional, which means there is at leasat a 9 in
n
9 in the last digit.
9 in the middle.
Have multiple 9.
Exercise 2 Review
factor.c
Optimization methods:
since anything bigger than for sure cannot divide !
If divides , then surely divides as well. See Proof of 2.
The above implies that we can count factors in pairs.
Note that if divides and , then
So, the supremum (the least upper bound) is .
We should then deal with the special case where is a perfect square (a perfet square has an odd numbero factors while any other integer has an even number of factors)
collatz.c
pattern.c
A Little Extension on prime.c
Question
How to find all primes less than or equal to .
Naive Solution
We iterate every integer from to (even if we exclude all even numbers, there are still steps. And checking if each integer is prime takes another steps in the worst case, so in total there are about steps -- Slow!
Optimized Solution
Using an array, we can speed up the algorithm. The algorithm we are using is called Sieve of Eratosthenes.
Consider all integers from to
Take 2 (which happens to be the smallest prime), and cross out all multiples of 2 in the list.
Take the un-crossed integer (which is 3 in this case), and cross out all muptiples of 3.
Iterate through the list while repeating the above process. We claim that: each time we come across an un-crossed integer , it will be a prime.
Stop when we encounter the first integer that is bigger than . We claim that from this integer onwards, all un-crossed integers are prime!
Number of operations in the worst case: upper-bounded by (fewer than ).
Last updated