Answer to Question #301880 in Python for sandy

Question #301880

Write a program to calculate the sum of cubes of differences of consecutive prime numbers entered from the keyboard. For e.g. for numbers 1,7,4,5,2,6,8,11 and 3, the program should calculate (7-5)3+(5-2)3+(2-11)3+(11-3)3

1
Expert's answer
2022-02-23T16:18:06-0500
def is_prime(x):
    if x < 2:
        return False
    if x == 2:
        return True
    if x % 2 == 0:
        return False
    
    p = 3
    while p*p <= x:
        if x % p == 0:
            return False
        p += 2
    return True

def sum_of_cubes(L):
    sum = 0
    p1 = None
    p2 = None

    for x in L:
        if is_prime(x):
            p1 = p2
            p2 = x
            if p1 is not None:
                sum += (p1 - p2)**3
    return sum

def main():
    line = input()
    L = [int(w) for w in line.split(',')]
    sum = sum_of_cubes(L)
    print(sum)

main()           

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS