---
# System prepended metadata

title: Question

---

# Question
Sum of 1 to 100 except the prime numbers.

### Method 1:
Check if the number from 1 to 100 is a prime number, and sum them up if they are not a prime number.

A simple and intuitive answer but too slow:

```
def isPrime(num):
    if num > 2:
        for i in range(2,num):
            if (num % i) == 0:
                return  False
                
    return  True

def sum(tail):
    s = 1
    for n in range(1, tail+1):
        if not isPrime(n):
            s = s + n

    return s

print(sum(100))

```


### Method 2:
To reduce the time consuming (Time Complexity), I found an algorithm called "Sieve of Eratosthenes" which is the most common algorithm and more effective way for finding all prime numbers upto given limit.

```
p = 2
n = 20
primes = list(range(p,n+1))            # Create a list with given all numbers.
while (p * p <= n):                    # Start filtering the multiples iteratively.
    for i in range(p*2, n + 1, p):     
        if i in primes:
            primes.remove(i)           # remove non-primes in the list
                
    p += 1
    
s = (1+n)*n//2                         # Sum of 1~n

print(s-sum(primes))                   # answer
```


### Reference:
https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
https://www.geeksforgeeks.org/python-program-for-sieve-of-eratosthenes/