Introduction to Algorithms, 2020-1
Week 4: 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. Goldbach's Conjecture

Goldbach's conjecture says that

Every even integer greater than 2 is the sum of two primes.

The conjecture seems obvious, but after more than 350 years it remains unproven.

Write a program that reads an integer N and checks whether Goldbach's conjecture is true for all integers that are ≤ N.

3. 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 10 · N. 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?

4. 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.

5. Rounded Square Root

Write a program that reads an integer n ≥ 0 and prints the square root of n, rounded up to the nearest integer. Do not use any floating-point numbers.

6. Ascending and Descending

Write a function largest that takes a list that is guaranteed to contain an ascending sequence of numbers followed by a descending sequence of numbers. For example, the list might be

[ 2, 4, 7, 10, 13, 15, 17, 14, 13, 5, 1 ]

The function should return the largest value in the input array. It is guaranteed that the input sequence will ascend at least once and descend at least once, i.e. the largest value will not be the first or last in the array. How efficient can this function be, in the worst case?