Week 4: Exercises

1. Starts With

Write a program that reads two strings S and T and writes 'starts' if S starts with T, otherwise 'no'. Do not use the built-in method startswith().

2. Contains

Write a program that reads two strings S and T, and writes 'contains' if S contains T, otherwise 'no'. Do not use the in operator.

3. Sum of All Numbers

Write a program that reads from standard input. Each input line will contain zero or more integers, separated by whitespace. The program should print the sum of all numbers in the input.

4. Consecutive Sum

Write a program that reads two integers N and T, each on its own line, followed by a line containing a series of integers, separate by whitespace. The program should determine whether any consecutive series of N values in the series have the sum T. If so, it should write those values to the output, separated by spaces. If there is no such series, write 'none'.

5. Letter Histogram

Write a program that reads a series of input lines and determines how many times each letter A-Z appears in the input. You should ignore case, considering 'a' and 'A' to be the same letter. Ignore any characters that are not letters from the Latin alphabet. The input text is guaranteed to contain at least one letter.

The program should print the most frequent letter with a count of its occurrences. It should also print a histogram showing each letter's frequency as a fraction of all input letters, rounded up to the nearest percent. For example, if 3.7% of letters are N, the program should print 'n: ****'.

Sample input:

The quick fox jumped over the lazy dog.
Then the dog got up and jumped over the fox.

Sample output:

Most frequent letter: e (9)

a: *
b: 
c: *
d: **
e: ***
f: *
g: *
h: **

…

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

7. Smallest Multiple

Solve Project Euler's problem 5:

What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

8. Sum Square Difference

Solve Project Euler's problem 6:

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

9. 10001st prime

Solve Project Euler's problem 7:

What is the 10 001st prime number?