Exercise 1

In this weeks's exercise, we will work with the following problems. The idea is that you are working with the problem with paper and pen; The teacher is on hand to answer questions and help. Some questions may be resolved on the board.

  1. Define a static method factorial which takes an integer n as a parameter and returns the integer n (n-factorial). The result is growing very fast with n so we can only use small n before the result becomes too large for the result type int, but we will live with that.
  2. Use the method from the previous task to write a program which prints a table of n, as follows:
       n        n!
       1         1
       2         2
       3         6
       4        24
       5       120
    
    The user decides the number of lines by giving the final n value as command line argument. You can get n by using the statement:
      int n = Integer.parseInt(args[0]);
    
    in the main method of the program.
  3. Euler's number e satisfies:

    e = 1 + 1/1! + 1/2! + 1/3! + 1/4! + …

    where … shall be understood in the sense that e is the limit of this series when the number of terms goes to ∞.

    First, write a method that takes integer n as argument and calculates the value of this sum with the last term 1/n!.

    Then write a program that uses the function and prints out a table of function values for n = 1,2, … 10th

  4. We will now expand the program from Lab 1 so that it can print a table like this:
    > java HarmonicSum 100 200 10
    Number of   Harmonic
    terms       sum
    100         5.187377517639621
    110         5.282234598243978
    120         5.368868287353397
    130         5.448591338265977
    140         5.522425264403279
    150         5.591180588643881
    160         5.655511224939744
    170         5.715952394926019
    180         5.772947721561
    190         5.826869007613198
    200         5.878030948121446
    
    The program now takes three command line arguments; the minimum number of terms, the largest number and the step, i.e. the difference in the number of terms between successive rows.

Optional

  1. Write a program that simulates rolling a pair of dice. You can simulate rolling one die by choosing one of the integers 1, 2, 3, 4, 5, or 6 at random. The number you pick represents the number on the die after it is rolled. The expression:
    (int)(Math.random()*6) + 1
    
    will select a random integer between 1 and 6. You can assign this value to a variable to represent one of the dice that are being rolled. Do this twice and add the results together to get the total roll. Your program should report the number showing on each die as well as the total roll. For example:
    The first die comes up:
    3
    The second die comes up:
    5
    Your total roll is:
    8