Week 4: Exercises

1. Reverse A String

Write a function reverseString(s: string): string that reverses a string. For example, reverseString(‘banana’) returns ‘ananab’.

2. First and Last

Write a function firstLast(n: integer): integer that returns the sum of the first and last digits in n. Do not use any strings.

3. Number Palindrome

Write a function isPalindrome(n: integer): boolean that returns true if n is a palindrome (i.e. it reads the same forward and backward) when expressed in decimal notation. Do not use any strings.

4. Random X's

Write a program that reads an integer N, and writes out a 10 x 10 block of dots (.), with X's in exactly N random positions.

Sample input:

10

Sample output:

. . . . . . . . . . 

. . . . . . . . . . 

. . . . . . . . . . 

. . . . X . . . . . 

. . X . . . X . . . 

. . . . . X . . X . 

. . . X . . . . X . 

. . . . . . . . X . 

X . . . . . . . . . 

. . X . . . . . . . 

5. Column with Largest Number

Write a program that reads an integer N followed by an N x N matrix of integers. The program should print the largest value in the matrix and the column number that contains it.

Input:

3
2 8 3
9 6 7
0 3 -1

Output:

Column 1 contains 9.

6. Largest Row or Column Sum

Write a program that reads an integer N followed by an N x N matrix of integers. The program should print the largest sum of any row or column in the matrix.

Input:

4
2 4 8 10
5 3 7 1
9 6 9 4
2 2 8 3

Output:

32

7. Smallest Multiple

(Project Euler, problem 5)

Write a program that finds the smallest integer that is divisible by every integer from 1 through 20. (Or, if you know how to solve this mathematically, you may simply compute the answer without writing a program at all.)

8. Sum Square Difference

(Project Euler, problem 6)

The square of the sum of the first 10 natural numbers is (1 + 2 + 3 + … + 10)2 = 552 = 3025.

The sum of the squares of the first 10 natural numbers is 12 + 22 + 32 + … + 102 = 385.

The difference between these is 3025 – 385 = 2640.

Write a program that finds the difference between (the square of the sum) and (the sum of the squares) of the first 100 natural numbers.

9. Number of Primes

Write a program that reads an integer N and prints the number of integers in the range [2, N] that are prime. For example, there are 8 primes in the range [2, 20], namely 2, 3, 5, 7, 11, 13, 17 and 19.

Enter N: 20
8

10. Simulated Rumor

Write a program that reads an integer N, representing a number of people. Simulate a rumor that spreads among these people as follows. A random person starts the rumor. They tell it to another person selected at random, who tells it to someone else, and so on, until someone hears the rumor who has already heard it before. At that point the rumor stops circulating. The program should produce output like this:

Enter N: 100
Person 41 heard the rumor.
Person 83 heard the rumor.
Person 22 heard the rumor.
…
Person 83 heard the rumor again.
14 people heard the rumor in all.