Introduction to Algorithms, 2021-2
Week 5: Exercises

1. Largest Prime Gap

A prime gap is the difference between two consecutive prime numbers. For example, 7 and 11 are consecutive primes, and the gap between them has size 4.

Write a program that reads an integer N ≥ 3 and prints the largest prime gap among primes that are less than N. The program should print the pair of consective primes along with the gap size.

2. Random Array

Write a program that reads an integer N and generates a random array of N integers in ascending order. The first number in the array should be 0, and the difference between each pair of consecutive array elements should be a random number from 1 to 10.

Next, the program should generate N new random integers in the range from 0 to 10N. The program should count how many of these integers are present in the array, and print this count.

If the input number N is large, what value do you think this program will print, approximately?

3. Integer Square Root

Write a program that reads an integer n ≥ 0 and prints the square root of n (if it is an integer), or otherwise 'Not a square'. Do not use any floating-point numbers. Your program should run in O(log n).

4. Prime-Counting Function

The prime-counting function π(x) returns the number of prime numbers that are less than or equal to x.

Write a program that reads an integer n and writes n lines of output. Each output line should contain an integer i (which will range from 1 to n over the output lines) plus the value π(i). Then run the program for n = 1000, and redirect the output to a file. Finally, use a graphing program to display a graph of the data you have generated.

5. Prime Experiment

Observe the following facts:

Consider the following hypothesis:

For all integers k ≥ 3, 2k mod k = 2 if and only if k is prime.

Do you believe that this is true, or false? Write a Python program to investigate this question.