Week 1: Exercises

1. Number Wheel

Consider this wheel with 10 numbers:

Write a program that reads two integers S and N on separate lines. S is the starting position of the wheel. N is a number of positions to turn the wheel, where a positive number indicates a counterclockwise rotation and a negative number is a clockwise rotation.

The program should print a single integer indicating the final position of the wheel.

2. Prime Counting

In number theory, the prime-counting function π(x) denotes the number of prime numbers that are less than or equal to x. (It is unrelated to the number π.)

a) Write a C# program that computes and prints π(1,000,000). Use trial division for primality testing.

b) Write the same program in Python.

c) Compare the running time of the two programs.

3. Longest String

Design and perform an experiment to determine the size of the longest string that C# will allow you to create.

4. Palindrome Test

Write a program that reads a string from the console and prints "palindrome" if it is a palindrome, otherwise "not"'.

5. Capitalized Words

Write a program that reads a string and writes it back out, capitalizing the first letter of every word.

6. Hailstone Sequence

A hailstone sequence of integers Hi starting from any integer H1 is defined as follows: If Hi is even, then Hi + 1 = Hi / 2; otherwise Hi + 1 = 3 Hi + 1. For example, the sequence starting from H1 = 10 is 10, 5, 16, 8, 4, 2, 1, 4, 2, 1, ...

Write a program that determines and prints the first value k for which the hailstone sequence starting at k rises above 1,000,000,000 before it reaches the value 1.

7. S Begins With T

Write a program that reads two strings S and T, each on its own line. The program should print "true" if S starts with T, "false" otherwise. Do not use any library functions.

8. Decimal to Binary

Write a program that reads a decimal integer and prints it out in base 2, i.e. binary.

9. Printing with Commas

Write a program that reads a single line containing an integer which may be arbitrarily large, and writes the integer with embedded commas.

Input:

28470562348756298345

Output:

28,470,562,348,756,298,345

10. Roll of the Dice

Write a program that reads an integer N and simulates rolling N 6-sided dice until all dice have the value 1. The program should print the number of rolls that were required. (On average, what number will the program print for a given N?)

11. Number of Words

Write a method that counts the number of words in standard input. Here, a word is any contiguous sequence of non-whitespace characters.