Lecture Notes on 03 Mar 2014 Loop Problems * Write a program that prompts the user to enter a postive number and then print the sum of its digits * Write a program that prompts the user to enter a postive number and then print the reverse of that number * Write a program that prompts the user to enter a postive number and then prints if it is prime or not. A prime number is divisible by one and itself. First prime is 2. * Write a program that prompts the user to enter a postive number and then prints if it is a perfect number or not. A perfect number is the sum of its proper divisors. * Write a program that prompts the user to enter a postive number n and then prints the nth Fibonacci number. n 0 1 2 3 4 5 6 7 8 9 10 F(n) 0 1 1 2 3 5 8 13 21 34 55 * Samuel Pepys asked Issac Newton which is more likely: getting a 1 at least once when rolling a fair die six times or getting 1 at least twice when rolling the die twelve times. Do a simulation of a thousand trials to determine the answer. In the first case, one trial is 6 throws and in the second case, one trial is 12 throws. * Draw the following pattern 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 * Draw the following pattern 1 2 3 4 5 1 2 3 4 1 2 3 1 2 1 * Draw the following pattern 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 def main(): # prompt user to enter a positive number: num = int (input ('Enter positive number: ')) # keep repeating till the user give correct input while (num <= 0): num = int (input ('Enter positive number: ')) # sum digits of a number n = num sum_digits = 0 while (n > 0): sum_digits += n % 10 n = n // 10 print ('Sum digits = ', sum_digits) # reverse number the number n = num rev_num = 0 while (n > 0): rev_num = rev_num * 10 + n % 10 n = n // 10 print ('Reverse number = ', rev_num) # get max and min of a set of numbers n = int (input ('Enter a number: ')) max_n = n min_n = n while (n > -1): if (n > max_n): max_n = n if (n < min_n): min_n = n n = int (input ('Enter a number: ')) print (max_n, min_n) # determine if a number is prime or not is_prime = True limit = int (num ** 0.5) + 1 for div in range (2, limit): if (num % div == 0): is_prime = False break if (is_prime): print (num, "is prime") else: print (num, "is not prime") # determine if a number is perfect or not sum_divisors = 0 limit = num // 2 + 1 for div in range (1, limit): if (num % div == 0): sum_divisors += div if (num == sum_divisors): print (num, "is perfect") else: print (num, "is not perfect") # print the nth Fibonacci term f = 0 if (num == 0) or (num == 1): f = num else: f1 = 0 f2 = 1 for i in range (2, num + 1): f = f1 + f2 f1 = f2 f2 = f print (num, f) main()