Euler first ten engineering problem solving ideas analysis

A multiple of 3 or 5 (multiples of 3 and 5)

We will be less than if all 10 natural number multiple of 3 or 5 listed, we give 3,5,6 and 9, and 23 thereof. Similarly, all of the following calculation 1000 is a multiple of 3 or 5 and a natural number.

Analysis: There are at least two solutions to this problem, the first solution is more direct, all multiples of 1,000 or less, or 3 to 5 are listed again seek to use the formula derived in python list requires only one line of code. The second idea is to use a summation formulas were determined all multiples of three and multiple of 1000 or less and a minus five and fifteen multiples, namely:
\ [S = \ sum_. 1} ^ {I = { 333} 3i + \ sum_ {i = 1} ^ {199} 5i- \ sum_ {i = 1} ^ {66} 15i = \ frac {3} {2} \ cdot333 (333 + 1) + \ frac {5} {2} \ cdot199 (199 +
1) - \ frac {15} {2} \ cdot66 (66 + 1) \] a first idea codes are as follows:

def main():
    ans = sum([x for x in range(1,1000) if x%3==0 or x%5==0])
    return ans

Second, the even Fibonacci (even Fibonacci numbers)

The Fibonacci sequence is derived from the sum of the first two, assuming that the first and the second number 1 and 2, the top ten were:
\ [1,2,3,5,8,13 , 21,34,55,89 \]
consider no more than four million of that deed Fibonacci numbers, which calculate the even Fibonacci numbers and deed.

Analysis: There are at least three solutions to this problem: first, we can write a function to calculate Fibonacci numbers deed, then screen out more than four million and one of the even number of summation; second idea is that we can directly from the formula that the number of deed a Fibonacci number of courtship, to avoid the screening process; third idea we can use the general term formula that Fibonacci numbers Fibonacci sequence, which can not use a loop to sum. Here I also briefly under three ideas.

Computing Fibonacci is a classic programming problem can be solved using a variety of methods, from the most simple recursive function solution, the iterative and dynamic programming solution, as well as matrix multiplication of the solution, of course, can also be used directly through item equation solver. The above method, the method of least efficient recursive functions not normally use. The algorithm general term equation as it relates to an irrational number, there is a problem of floating-point calculation error, here we are not involved. As for iterative calculations, and dynamic programming matrix multiplication of these three methods is not much difference in the small scale of the problem run time, so I will only introduce iterative calculations, detailed information related to other methods you can search the Internet, it is easy to you can be found.

First look at the first idea. We all know the definition of Fibonacci Fibonacci number sequence, after setting the first and second terms (assuming that the subject is both one and two respectively), after each of which is equal to the sum of its two ago, so we use a temporary variable to hold the middle of the calculation process, and the final result is obtained by iterative calculation. Suppose the start \ (A =. 1, B = 2 \) , then in the next step (B \) \ assigned to \ (A \) , the \ (a + b \) a value is assigned to \ (B \) , so iterative process that actually generate Fibonacci number Fibonacci sequence of. To solve the problem of the title, just long enough to generate a Fibonacci number, which can be screened even number plus the total of less than four million.

The second idea is to take into account the requirements subject only to the even Fibonacci numbers are summed, this time determined that all of the Fibonacci number deed seem less economical, there is just no way to even-Fibonacci? Look above Fibonacci number, we can see that the second term is even, two odd-fifth interval is an even number, spacing and then two eighth and even. The reason for exhibiting such a law, because the law of parity addition caused. We know that an odd number plus an odd number must be an even number, an even plus an even number is an even number, however odd it must be coupled with an even number is an odd number. In the above series, the first term is an odd number, the second term is an even number, the third term is an odd number, the fourth term is equal to the second plus third, i.e. an odd plus an even number, the fourth item is odd; the fifth is equal to the third plus the fourth, both of which are odd, so the fifth must be an even number. And so on, eighth, eleven, fourteen and other other items is even. The meaning of the questions we set \ (of F_1 =. 1, 2 F_2 = \) , there are:
\ [\ the aligned} {F_n the begin = & F_ {+}. 1-n-n-F_ {\\ &-2} = {N- F_ 2} + F_ {n-3 } + F_ {n-3} + F_ {n-4} \\ & = 2F_ {n-3} + F_ {n-2} + F_ {n-4} \\ & = 2F_ {n-3} + (F_ {n-3} + F_ {n-4}) + (F_ {n-5} + F_ {n-6}) \\ & = 3F_ {n-3} + F_ {n-4} + F_
{n-5} + F_ {n-6} \\ & = 4F_ {n-3} + F_ {n-6} \ end {aligned} \] obviously, by our above inference can be seen, \ (F_n,. 3-n-F_ {},}. 6-n-F_ {\) are even, then we can represent them as a new number of columns, called even Fibonacci number, the first two, eight second recursive formula is as follows:
\ [EF_n 4EF_ = {} +. 1-n-n-EF_-2 {} \ Quad (EF_1 = 2, = EF_2. 8) \]
Then we can according to the recurrence formula to calculate all even Fibonacci numbers, use half the amount of calculation is omitted iterative calculation method above.

The third idea is to directly use the Fibonacci number Fibonacci sequence general term formula to calculate the Fibonacci numbers, and the screening of which no more than four million of the even and summed. The advantage of this method is its time complexity is \ (O (1) \) , is the most efficient algorithm. The disadvantage is that the number of term formula Fibonacci Fibonacci sequence involves irrational numbers, floating point calculations and thus affect the accuracy of the problem will appear when N increases, the more serious this floating point error. Although we may have to use more high-precision floating-point number or a special external libraries to solve this problem, but it certainly introduces more complexity, so here we do not introduce this approach in detail. Interested students can be found in Wikipedia .

The second idea codes are as follows:

def main(N=4e6):
    a,b = 2,8
    arr = [a,b]
    while True:
        a,b = b,4*b+a
        arr.append(b)
        if b > N:
            return sum(arr[:-1])

Third, the maximum quality factor (largest prime factor)

13195 prime factors were 5,7,13 and 29,600851475143 largest prime factor is how much?

Analysis: method for solving large prime factors, the most commonly used method for short-division, i.e., for any natural number greater than N 2, the first divided by N 2, and then the resulting quotient (N / 2) divided by 2, until the quotient is not divisible by 2, when the dividend is incremented by comparing the square is smaller than the dividend, is less than the supplier then divided by 3, such as not divisible, is divided by 5 (as a multiple of 2, i.e., all the even factor has in the first round constantly divided by 2 is ruled out, then so be plus two). So the cycle continues until the square is no longer less than the dividend the divisor, then the loop is exited, N is the maximum prime factor of the finally obtained. In actual implementation, be divided into two cycles, determining the outer loop is less than the square dividend divisor, the dividend can be determined whether the inner loop divisor is divisible.

def main(n=600851475143):
    i = 2
    while i * i < n:
        while n%i == 0:
            n /= i
        i += 2 if i>2 else 1
    return n

Fourth, the maximum number of palindrome product (largest palindrome product)

Palindrome that is read from both sides are the same number, the product of two of the largest double-digit palindrome is \ (9009 = 91 * 99 \) , find the product of two three-digit greatest return number of text.

Analysis: The topic that you want to find the maximum number obtained by multiplying three-digit palindrome two, so this is only the minimum number \ (100 ^ 2 \) , the largest only \ (999 ^ 2 \) , that is, He said that in the interval \ ([10000,998001] \) between the six-figure range in the vast majority, and subject also requires the largest palindrome, so we assume that the request is a six-digit number, see You can not find a number to meet the requirements. Assuming that this is a six-digit \ (ABCCBA \) form, there are:
\ [\ the aligned the begin {} 'ABCCBA'. 5A & ^ = 10 + 10 + 10 ^ ^ 4B. 3C + 2C + 10B + 10 ^ \\ A & = 100001a + 10010b + 1100c \\
& = 11 (9091a + 910b + 100c) \ end {aligned} \] can clearly be seen to meet the requirements must be a multiple of six-digit 11, thus detecting the six digit prior whether it is a palindrome, we can check to make sure it is a multiple of 11, so you can speed up verification. We can use the list in descending generate a product of formula derived three-digit two, then detect whether the product is a multiple of 11, and if it is a palindrome, and finally selecting the maximum value of the list is also desired. Note that, herein defined with a Lambda expression determines whether a particular number is a function of the palindrome, the method is converted into a digital string, and then determines whether the string is equal to its inverting string.

def main():
    r = range(999,99,-1)
    is_palindrome = lambda x : str(x) == str(x)[::-1]
    ans = max([i*j for i in r for j in r if (i*j)%11==0 and is_palindrome(i*j)])
    return ans

Fifth, the least common multiple (smallest multiple)

2520 is the smallest number can be from one to ten all natural numbers divisible, is the least common multiple of the natural numbers from one to ten, from the least common multiple of one to twenty seeking all natural numbers.

Analysis: This question is at least two problem-solving ideas, the first idea is to write a function to calculate the least common multiple, then find the least common multiple of all integers of one to twenty. Have a greatest common divisor calculation function in the python math library, we can Euclidean formula, introduced from the least common multiple of the two numbers greatest common divisor of two numbers, i.e., for any natural number \ (a, b \) , provided the greatest common divisor of two numbers \ (GCD (a, B) \) , the least common multiple of the two numbers
\ [lcm (a, b) = \ frac {ab} {gcd (a, b)} \]
Accordingly, we can first find the least common multiple of two numbers, then the third and least common multiple of the number of seeking the least common multiple, where you can use reduce()the function multiple iterations to obtain the least common multiple of the number. This line of thinking good performance in the small scale of the problem, you can give the answer to the problem within a few microseconds of the title. But we can be more in-depth analysis of the problem, we can find a more efficient way.

Let's look at a simplified issue, the title says all integers of the least common multiple of one to ten is 2520, this number can find out how? We first of all the number of two to ten factorization qualitative results are as follows:
\ [[2: 2,3: 3,4-: 2 ^ 2,5: 5,6: 2 \ times3,7: 7, 8: 2 ^ 3,9: 3 ^ 2,10:
2 \ times5] \] To find a number of all numbers divisible above the minimum, we can start looking from all the prime numbers less than ten, first look at the first two prime numbers , the largest index list above two three, which is the prime factor VIII decomposition, if a number can be divisible by the cube of eight is two, then it must be divisible by two and four, which is the secondary II and one side of divisibility. Let's look at three tables is the second largest index of three, it can be bound to be divisible by three the number of square feet of divisible by three. The next prime number five, the table is a five largest index, so this number should be divisible by five. The last prime number seven, is a maximum index, so this number should be divisible by seven. In summary, divisible table the minimum number of all numbers should be the prime factorization of the number of all, the maximum power of the respective prime numbers multiplied result, i.e. \ (2 ^ 3 \ times3 ^ 2 \ times5 \ times7 = 2520 \ ) .

Obviously we directly use this algorithm to solve the problem of the title, but we can still make further improvements to this algorithm. According to this algorithm, we need all the prime factorization to strike a maximum power of each prime numbers, this calculation is quite time-consuming, there is no faster way? Because we care only about the maximum power of the respective primes, without regard to specific prime factors of each number of decomposition way, by far the largest power of any prime numbers is making it count in the end no more than, for example, find the least common multiple of one to ten, and end number ten, the highest power of two of the only three, not four, because two fourth power equal to Congress within ten; the same token, the highest power of three can only be two, three cubic also because It will be greater than ten. And so on, V and VII of the index can only be one, because of this they are more than ten square. Here we see another optimization techniques, that is, we only require a maximum power of those prime numbers greater than the number whose square is not the end, because those square of prime number greater than the number of end points, its index is a necessity. Finally, according to the above reasoning, highest power of a prime number, just required to the prime number raised to a number of end points is true logarithm of the number and the rounding can, that is:
\ [P_i ^ E \ Le N \ Rightarrow e = \ lfloor ln (
N) / ln (p_i) \ rfloor \] for the title in the size of the problem, with respect to the advantages of the second algorithm the second algorithm is not obvious. On my computer, the first algorithm takes 5.5 microseconds, the second algorithm takes 33.6 microseconds; but when \ (N = 1000 \) , the first algorithm takes 938 microseconds, and the second algorithm takes 618 microseconds, the second algorithm time is shorter. Further increase in scale of the problem, when the \ (N = 10 ^ 4 \ ) , the first algorithm takes 63.5 ms, 7.22 ms Processed second algorithm; when \ (N = 10 ^ 5 \ ) , the first algorithm takes 5.85 seconds, the second algorithm takes 198 milliseconds, the efficiency gap between the two has been very different. In general, the time complexity of the algorithm a first close \ (O (^ n-2) \) , the second time complexity of the algorithm close\ (O (nlogn) \) . Code that implements two algorithms are as follows:

# approach 1, time complexity = O(n^2)

from math import gcd
from functools import reduce

def lcm(n):
    def lcm(a, b):
        return (a * b) // gcd(a, b)
    return reduce(lcm, range(1,n+1))

# approach 2, time complexity = O(nlog(n))

from sympy import primerange
from math import sqrt,log,floor

def main(n=20):
    primes = list(primerange(1,n))
    i,ans = 0,1
    while primes[i] < sqrt(n):
        e = floor(log(n)/log(primes[i]))
        ans *= (primes[i])**e
        i += 1
    for p in primes[i:]:
        ans *= p
    return ans

Six, and the difference between the square and the square of

First ten square natural number and is:
\ [1 ^ 2 + 2 ^ 2 +. 3 ^ 2 + \ cdots + 10 ^ 2 = 385 \]
and the first ten natural numbers and the square is:
\ [(1 + 2 +3+ \ cdots + 10) ^ 2
= 55 ^ 2 = 3025 \] difference between the two is \ (3025-385 = 2640 \) , summing the square of the number of the first one hundred square natural and between difference.

Analysis: This problem can be solved using direct summation formula, then:
\ [S (n-) = (\ {FRAC. 1} {n-2} (n-+. 1)) ^ 2- \ FRAC. 1 {{}}. 6 n-( n + 1) (2n + 1
) = \ frac {1} {12} n (n-1) (n + 1) (3n + 2) \] is substituted into \ (S (100) \) can be directly calculated from the results, code show as below:

def main(n=100):
    ans = n*(n-1)*(n+1)*(3*n+2)/12
    return int(ans)

Seven, the first 10001 prime number

Number six quality listed before, we can see that the sixth prime number is 13, then the first 10001 prime number is how much?

Analysis: In general, for the first \ (n-\) prime numbers \ (P_n \) , satisfy the following inequality (see prime-counting function ):
\ [LN (NLN (n-)) -. 1 <\ FRAC {P_n} {n- } <ln (nln (n)
) \] here we focus only on the boundary can be obtained \ (P_n <NLN (NLN (n-)) = NLN (n-) + NLN (LN (n-)) \) , we to filter out all prime numbers from 2 to the upper bound, then take the first prime number 10001 which, then results.

from sympy import primerange
from math import log,ceil

def main(n=10001):
    upper_bound = ceil((log(n)+log(log(n))) * n)
    primes = list(primerange(1,upper_bound))
    return primes[n-1]

Eight, the sequence of the largest product

In the following digits 1000, the product of the maximum number of four consecutive \ (8 * 9 * 9 * 9 = 5832 \) :

IMG

Find the maximum number of consecutive product of thirteen, this product is how much?

Analysis: This problem solving ideas more direct, divided into the following steps: 1) The above deposited into digital TXT file, and imported into the python with a LIST; and 2) LIST from the beginning until the first 0 987 bits are evaluated in order, and the product of the number of bits stored in thirteen consecutive to the result of the LIST; 3) selecting the maximum value of the results obtained LIST result.

from functools import reduce

def main():
    with open('euler/ep08.txt','r') as f:
        data = ''
        for line in f.readlines():
            data = data + line.strip()
    res = []
    for i in range(988):
        sub = [int(x) for x in data[i:i+13]]
        prod = reduce(lambda x,y:x*y, sub)
        res.append(prod)
    return max(res)

Nine, special triple the number of Pythagoras

Pythagorean triples the number three is the set of natural numbers a class, wherein \ (a <b <c \ ) and \ (A ^ B ^ 2 + 2 ^ 2 = C \) , for example, \ (^ 3 2 + 2 = 4 ^ 5 ^ 2 \) . Pythagorean triples such that there is only a set number \ (A + B + C = 1000 \) , seeking \ (ABC \) .

Analysis: This problem solving ideas at least two, a first idea is as follows: To make more general problem-solving ideas, provided triangular circumference \ (P \) , there \ (a + b + c = p \) , so \ (C = PAB \) , there are:
\ [A ^ B ^ 2 + 2 ^ 2 = C = (PAB) = P ^ 2 ^ 2 + 2 + A ^ B ^ 2-2pa-2PB + 2ab \]
can be obtained:
\ [B = (P ^ 2-2pa) / (. 2A-2P) \]
is such that \ (B \) is an integer \ (P \) and \ (a \) can be to meet the requirements of the subject, thereby to obtain a set of Pythagorean terpolymer meet the requirements. In addition, without loss of generality, we assume that \ (A \ Le b <c \) , and because \ (A + b + c = the p-\) , there should \ (A <the p-/ 3 \) , which can be reduced we need to filter the number \ (a \) range. Since the subject has been described in \ (p = 1000 \) there is only one set terpolymer Pythagoras, then we need to write only a function to find a suitable \ (A \) values such that \ (B \) is an integer, once find can be calculated \ (c \) and returns the product of the three.

Need to use the second approach Euclidean formula for \ (m> n-> 0 \) , we know that the number may be composed of three Pythagorean terpolymer:
\ [A = K (n-m-2 ^ ^ 2), b = 2kmn, c
= k (m ^ 2 + n ^ 2) \] there is:
\ [A + B + C = K (m ^ 2-n-^ 2 + 2mn-+ m ^ 2 + n-^ 2) = k (2m ^ 2
+ 2mn) = 2km (m + n) = 1000 \] then we can get \ (m (m + n-) = 500 / K \) , apparently \ (m <m + n \ ) , while \ (m, n \) are \ (500 / k \) factor, then we can get \ (m <\ sqrt {500 / K} \) . We have \ (= n-500 / K \ CDOT mm <m \) , there \ (m> \ sqrt {250 / K} \) , i.e. we may obtain \ (m \) the range is \ ([\ sqrt {250 / K}, \ sqrt {500 / K}] \) . Now we assume \ (. 1 K = \) , then \ (m \ in [15.81,22.36] \) , of which only an integer 16,17,18,19,20,21, apparently only be a factor of 20 to 500, there \ (m = 20 is,. 5 n-= \) , then:
\ [A = 20 ^ 2-5 ^
2 = 375, b = 2 \ times20 \ times5 = 200, c = 20 ^ 2 + 5 ^ 2 = 425 \] The \ (a, b, c \ ) of the three phase take is the subject of the request. Obviously the second approach can be directly calculated from the results of the pen, so here we only listed the first idea of the code:

def main(p=1000):
    for a in range(1,p//3):
        n,d = p**2-2*p*a,2*p-2*a
        if n % d == 0:
            b = n/d
            c = p-a-b
            return int(a*b*c)

Ten, prime numbers and

\ (10 \) or less and is a prime number \ (2 + 3 + 5 + 7 = 17 \) , find all prime numbers and two million or less.

Analysis: Detailed analysis of this topic, see my other article .

Guess you like

Origin www.cnblogs.com/metaquant/p/11810784.html