Exercise - 4 Examples on Control Flow

4 A) Find the sum of all the primes below two million.
B) 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 four million, find the sum of the even-valued terms.
A) AIM: Find the sum of all the primes below two million.

SOURCE CODE

import math
primes = [True] * 2000000 


def isprime(primes, x):
    for i in range(x+x, len(primes), x):
        primes[i] = False


for x in range(2, int(len(primes) ** 0.5) + 1):
    if primes[x]: 
     isprime(primes, x)

summ=0
for i in range(2,len(primes)):
    if primes[i]:
        summ=summ+i
print("Summ of all primes below two million is:",summ)

OUTPUT

Sum of all primes below two million is: 142913828922


B) AIM:By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even valued terms.

SOURCE CODE:

a=0
b=1
c=a+b
sum=0
while c<=4000000:
    if c%2==0:
        sum=sum+c
    a=b
    b=c
    c=a+b
print ("Sum of even valued terms in Fibonacci is : ",sum)

OUTPUT:

Sum of even valued terms in Fibonacci is :  4613732

No comments:

Post a Comment

Total Pageviews