Question

Find the sum of the first n composites that do not end in the digit 2....

Find the sum of the first n composites that do not end in the digit 2. (n = 6 ⇒ 51) using python

0 0
Add a comment Improve this question Transcribed image text
Answer #1

code screenshot:

o/p:

code:

# importing the count for infinite loop
from itertools import count

# function will tell if the number is composite or not
def isComposite(num): 
  
    # Corner cases 
    if (num <= 1): 
        return False
    if (num <= 3): 
        return False
  
    # This is checked so that we can skip  
    # middle five numbers in below loop 
    if (num % 2 == 0 or num % 3 == 0): 
        return True
    i = 5
    while(i * i <= num): 
          
        if (num % i == 0 or num % (i + 2) == 0): 
            return True
        i = i + 6
          
    return False

# driver code

n = int(input('Enter the number of terms: '))

# initialize the counter
counter = n

# initializing the variable to hold the sum
sum_composite = 0

# for loop will execute till infinity until the break condition is interpreted
for num in count():

    # check if the number is composite or not
    if isComposite(num):

        # check if the number ends with 2 or not
        if num % 10 != 2:

            sum_composite += num

            # decrement the counter
            counter -= 1

    # if the counter becomes 0 break the loop
    if counter == 0:
        break

# display the sum
print('Sum of first {} composite numbers is: {}'.format(n, sum_composite))

For help please comment. Thank You

Add a comment
Know the answer?
Add Answer to:
Find the sum of the first n composites that do not end in the digit 2....
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT