# MIT : Ps1b

## Ps1b - 2nd assignment, part b

Write a program that computes the sum of the logarithms of all the primes from 2 to some number n, and print out the sum of the logs of the primes, the number n, and the ratio of these two quantities. Test this for different values of n. […] you should see the ratio of the sum of the logs of the primes to the value n slowly get closer to 1.

I spent more time googling logarithms and ratios than python code for this one. Once I had a tenuous grasp on the mathematical concepts (hopefully), it was easy to find python math functions that do all the heavy lifting.

We were allowed to borrow code from our last solution, of course. In fact, that was suggested.

#!/usr/bin/env python # Problem Set 1b # Name: Tony Baldwin # Collaborators: 0 # Time: 1.5 hr from math import * n = input("Please enter a number: ") primes = [2] logs = [0.69314718055994529] q = 3 while q < n: for i in primes: if q % i == 0: break else: l = log1p(q) primes.append(q) logs.append(l) q += 2 slog = sum(logs) print("The sum of the logs of the prime numbers less than or equal to %s is %s." % (n, slog)) rat =(slog / n) print("The ratio of these values is %s:%s, which is equal to %s." % (slog, n, rat)) print("Have a nice day.") exit

In action:

Some results:

[526][tony.deathstar: ps1]$ ./ps1b.py Please enter a number: 20 The sum of the logs of the prime numbers less than or equal to 20 is 16.9607105634. The ratio of these values is 16.9607105634:20, which is equal to 0.848035528172. Have a nice day. [527][tony.deathstar: ps1]$ ./ps1b.py Please enter a number: 200 The sum of the logs of the prime numbers less than or equal to 200 is 189.925466664. The ratio of these values is 189.925466664:200, which is equal to 0.949627333318. Have a nice day. [527][tony.deathstar: ps1]$ ./ps1b.py Please enter a number: 2000 The sum of the logs of the prime numbers less than or equal to 2000 is 1941.54423099. The ratio of these values is 1941.54423099:2000, which is equal to 0.970772115494. Have a nice day. [527][tony.deathstar: ps1]$ ./ps1b.py Please enter a number: 20000 The sum of the logs of the prime numbers less than or equal to 20000 is 19807.2771139. The ratio of these values is 19807.2771139:20000, which is equal to 0.990363855694. Have a nice day.

So…I have this one working. Initially I was confused about the log thing, and someone had to clarify for me that this meant “natural logs (based e)” and not base 10. I haven't a clue what the difference is. Recall, I'm a linguist, not a mathematician. I suppose, this course belonging to the engineering department, they assume a level in mathematics beyond what I recall. I `did`

take a course in calculus, once, but that was in, hmmm… That was in 1987/88. I haven't really used any of that since.

tonybaldwin September 04, 2011, at 03:34 AM

~~DISQUS~~