CSC 131 - Introduction to Computer Science

### Program 1: Count Negative

Write a Python program, CountNegative.py, which allows a user to enter as many numbers as they want, one at a time.  When they hit Enter with no input, the program will stop asking them for numbers and prints out how many of the numbers were negative.  The output also includes how many total numbers were entered.  Here is an example run:

Enter a number: 5

Enter a number: 6

Enter a number: -8

Enter a number: -4

Enter a number: 2

Enter a number: 0

Enter a number:

You entered 2 negative numbers out of 6 total numbers.

### Program 2: Calculating sin and cos

You can compute sin(x) and cos(x) using the following power series:

Write a loop to calculate the sine of a number input by the user.

·         We can use math.pow(a, b) to raise a number to a power or use a**b.

·         To calculate the factorial of n, we can use math.factorial(n).

·         Initialize a sum to 0.

·         Each iteration of the loop adds a new term to a running sum.

·         In other words, in each loop iteration, for sin(x), you would add sign*math.pow(x, count)/math.factorial(count) to a running sum.

·         At the bottom of the loop, be sure to increment the counter by 2 each time through the loop.

·         At the bottom of the loop, be sure to flip the value of “sign”.   Here’s a neat trick:  Initialize sign to 1.  Then sign = -1*sign will make sign negative if it was positive; it will be positive if it was negative.

·         I would make a separate loop for calculating the cosine to make thing simpler.

When does the loop stop?  If we want our calculation accurate to 10 decimal places, we will set a flag to stop the loop when the term being added is less than 0.00000000001.

Here is an example run:

Input a value in radians: 0.1

sin(0.1) = 0.0998334166

cos(0.1) = 0.9950041653

Here is another example run:

Input a value in radians: 3.14159

sin(3.14159) = 0.0000026536

cos(3.14159) = -1.0000000000

### Program 3: Is it prime?

A prime number is an integer greater than 1 and divisible only by itself and 1.  The first seven prime numbers are 2, 3, 5, 7, 11, 13, and 17.  Write a program that asks the user for a positive integer and then tells the user whether that number is prime or not.

How?   Try dividing by all the numbers smaller than the number (except 1).  If the remainder is ever 0, then the number is not prime.  If you get through the entire loop without ever finding a divisor that divides evenly into the number, then it must be prime.

Some example runs:

Enter a positive integer: 5

Yes, 5 is prime.

Enter a positive integer: 100

No, 100 is not prime.

Enter a positive integer: 101

Yes, 101 is prime.

Enter a positive integer: 1001

No, 1001 is not prime.

No, 1000001 is not prime.

Enter a positive integer: 1000000000001

No, 1000000000001 is not prime.

Enter a positive integer: 1023947

Yes, 1023947 is prime.