PE1 (AY18/19)
Problems
1. Vote
This is a "give-away" question.
2. Newton
In math.h
library in C, there is a function called fabs(x)
, which will return the absolute value of a floating-point argument x
.
We may need the idea of getting when we want to judge whether two double
are equal. However, if we only want to know which double
is bigger enough, we can just use the operators , that's enough.
3. Goldbach*
The good way to write prime
.
Note that using this method (i * i <= n
) can save us from the trouble of dealing with type casting when using the sqrt()
from math.h
library.
However, below is mine version of prime.c
, which may be a little bit faster.
4. Digits*
The most important idea in this probelm is to define two variables (so that we won't use arrays
here) to store:
The digit(0-9) of the longest sequence
The length of the longest sequence
There is a trivial case that may be ignored in this probelm if you use while
loop. That is when you input num
as . To deal with this case correctly, you should initialize the variables correctly and use do-while
loop.
In this program, the use of current_digit
is awesome! Actually, it serves the purpose of previous_digit
and n % 10
at the first of the loop acts as the true current_digit
. Initializing the current_digit
to be n % 10
deals with the problem of there is no previous_digit
at the start in an elegant way.
The use of do-while
loop also guarantees that we will enter the loop at least once, which deals with the trivial case of as well.
5. Square
The "heart" of this problem is pattern recognition. Below are the patterns that are crucial:
The first and last rows
(row == 1 || row == width)
are where we have to draw##...#
The second and penultimate rows
(row == 2 || row == width - 1)
are where we have to draw#...#
The rest
(row == 3 && row <= width - 2
, where we have to draw#...#
, but with inner squares with the recursionprint_square(row - 2, width -4)
.
Tips
Always regard real numbers as
double
type variable!Include the function
prime
in your cheatsheet!When to pay attention to the Big Number input in the question involving
prime
? The rule of thumb is to pass all the test cases, these cases should be strick enough! Also, theis_prime(num)
function provided here 3. Goldbach* should be quick enough!!!
Last updated