Python - Week 9 - Simple Math problems

This week I tackled 3 math problems. Not much of Python here, but I wanted to check out how Math problems are handled. In the end, it all depends on the algorithm deployed and the libraries/constructs available.

Here is the first problem:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.


This is not a complicated problem and the solution itself is pretty straightforward. The only Pythonic construct used here is the else for the loop which is executed only if the for loop runs successfully (which it anyway does here). The more interesting use of this else statement would have been the cases where we may break the loop.

Now lets look at the second problem:

Each new term in the Fibonacci sequence is generated by adding the previous two terms.
By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence whose values do not exceed the given argument, find the sum of the even-valued terms.


Again, there is nothing specific to Python here. This something that could have been done as effectively using C or any other language.

Or may be I need to learn more Python.

This is the final problem I worked on this week:

The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 6458592734432 ?


This solution has some meat in it. Some points to consider:

  1. We use sympy library isprime function to check if we have a prime number.
  2. Python has a fancy feature called closure, which allows for defining function within a function. As I read about it, I could see many ways it is important. Though it is not relevant here, I used this feature in Lines 16 - 21. This isolates the use case of computing the upper bound. However, it could be more useful to return functions (perhaps based on some argument).
  3. Line 26 shows how you can use a loop that decrements. It starts with an upper bound, goes until the lower bound and third parameter dictates the steps. Note that I want the loop to run until n=2. So I specify 1 as the terminating value.
  4. Finally, like other languages, Python uses short circuit evaluation of conditions. I expect remainder division to be less expensive than isprime. So I call call it first.

Comments

Popular posts from this blog

Python - Week 8 - Dictionaries, Tuples, Sorting and Filtering

Python - Week 3 - Lists, Tuples, Slicing, Math Functions

Python - Week 5 - Comprehensions