Python - Week 10 - Math Problems
Few more Math problems solved using Python
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
So for example sum of squares of first 100 natural numbers from 1 to 100 is 25502500.
And square of sum of first 100 natural numbers from 1 to 100 is 338350.
Here is the code:
Again, a simple solution to a simple problem.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
So for example sum of squares of first 100 natural numbers from 1 to 100 is 25502500.
And square of sum of first 100 natural numbers from 1 to 100 is 338350.
Here is the code:
- I have separated the two functions for modularity
- Line 4 shows how comprehensions can be used to solve these kind of problems.
- Line 6 is the way to sum over iterables. Here sum just takes in an iterable (could have been a dictionary or a map as well) and does the magic. No need to write additional code here.
- An object is iterable if it is either a physically stored sequence in memory, or an object that generates one item at a time in the context of an iteration operation. List objects are considered iterable because they support the iteration protocol—they respond to the iter call with an object that advances in response to next calls and raises an exception when finished producing values.
Next problem:
How do you calculate Least Common Multiple (LCM) of n consecutive numbers?
How do you calculate Least Common Multiple (LCM) of n consecutive numbers?
- Find all prime numbers from 2 onwards that are less than or equal to n
- For each such prime number find the highest power less than n
- LCM is the product of all numbers in step 2
- So if n is 20, the prime numbers are 2,3,5,7,11,13,17,19
- Now 2**4 is 16 which is highest power less than 20
- Similarly, 3**3 is 9 which is highest power less than 20
- There are no more powers that are less than 20. So LCM will be 16 * 9 * 5 * 7 * 11 * 13 * 17 * 19
Now lets look at the code
A colleague of mine stopped by to discuss Collatze Sequence problem. The problem is stated as follows:
The following iterative sequence is defined for the set of positive integers:
n → n/2 (n is even)
n → 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
Here is a simple Python implementation
Comments
Post a Comment