Skip to main content

more options

Self-check exercise: User-defined functions

  1. Write a function aprime(m) that has an input parameter m. Function aprime(m) returns 1 if m is prime, and 0 otherwise. Remember to write a concise comment to describe the function, including its parameters under the function header.
  2. A twin prime is a pair of primes such that if p is a prime, p+2 is also a prime. The larger prime in the pair is called the big prime, while the smaller prime is called the little prime. For example, in the twin prime pair (3,5), 5 is the big prime while 3 is the little prime. Write a function lastTwinPair(n) that will, given a number n greater than or equal to 3, return the last (largest) twin prime pair smaller than or equal to n. Use function aprime from the previous question! This function returns two values!
  3. Write a function vectorQuery(v,n,r) to determine whether the number r appears in the first n cells of vector v. The function returns 1 if r is in the first n cells of v and 0 otherwise. Your function assumes that v is a vector of numbers, n is a positive integer, and r is a number. Use a loop to do the search. Make sure that the loop index does not go out of bounds (if n is greater than the length of vector v).
  4. How many rolls of a fair die does one need to accumulate at least 20 points? Of course one needs at least 4 rolls (as in 6 + 6 + 6 + 2 or 6 + 5 + 4 + 5) and at most 20 rolls (getting 20 1's in a row). However these sittuations are rather unlikely! Hence, we ask ourselves: what is the most likely number of times that one has to roll a die? Write a program to answer this question.
    • First write a function rollsUntil(p) that simulates one experiment run, i.e. rolling the die several times until at least p points have been accumulated and counting how many times the die was rolled. The function should return the required number of rolls.
    • Test this function.
    • Then write a script that calls the function rollsUntil(p), with p = 20, many times (say 10000).
    • Use an array counts to summarize the results, as follows. Start with counts being a vector of zeros of length 20. After each run, increment component counts(n) by one, if the run took n rolls of the die.
    • After running your program, sum(counts) should equal 10000 (the total number of runs) and [maxcount, maxn] = max(counts) will yield the maximum count and the value of n for which this count is obtained. Thus, maxn will be the most likely number of rolls of the die to get 20 points.