Question

I want to print all the prime numbers from 1 to 10 but nothing gets printed when i run the program

c=0
nums = []                   
k=0
for a in range(1,11):          
    for b in range(1,11):
        if a%b==0:          
            c = c+1        
    if c==2:                  
        nums.append(a)      
        k = k+1 
for d in nums:              
    print nums[d]            
Was it helpful?

Solution 2

You should reset c to zero before the beginning of each inner loop:

nums = []                   
for a in range(1,11):
    c = 0         
    for b in range(1,11):
        if a%b==0:          
            c = c+1        
    if c==2:                  
        nums.append(a)      
for d in nums:              
    print d

Additionally, you should use print d, since the for-loop already gives every element in nums.

Using a list comprehension is generally faster and considered more pythonic than using a for-loop.


There are many different ways of calculating prime numbers. Here are some of them.

Here is your original algorithm, with some improvements;

def prime_list(num):
    """Returns a list of all prime numbers up to and including num.

    :num: highest number to test
    :returns: a list of primes up to num
    """
    if num < 3:
        raise ValueError('this function only accepts arguments > 2')
    candidates = range(3, num+1, 2)
    L = [c for c in candidates if all(c % p != 0 for p in range(3, c, 2))]
    return [2] + L
  • For primes >2, they must be odd numbers. So candidates should contain only odd numbers.
  • For an odd number c to be prime, one must ensure that c modulo all previous odd numbers (p) must be non-zero.
  • Lastly, 2 is also prime.

A further improvement is to restrict p up to sqrt(c):

import math

def prime_list2(num):
    if num < 3:
        raise ValueError('this function only accepts arguments > 2')
    candidates = range(3, num+1, 2)
    L = [c for c in candidates if all(c % p != 0 for p in
         range(3, int(math.sqrt(c))+1, 2))]
    return [2] + L

Another implementation:

def prime_list3(num):
    num += 1
    candidates = range(3, num, 2)
    results = [2]
    while len(candidates):
        t = candidates[0]
        results.append(t)
        candidates = [i for i in candidates if not i in range(t, num, t)]
    return results

This starts off with a list of candidates that contains all odd numbers. Then is calculates a new list of candidates by removing the first number of the previous list and all all multiples of it.

Let's look at the speed of the algorithms.

For small numbers, the original prime_list is the fastest;

In [8]: %timeit prime_list(10)
100000 loops, best of 3: 8.68 µs per loop

In [9]: %timeit prime_list2(10)
100000 loops, best of 3: 10.9 µs per loop

In [10]: %timeit prime_list3(10)
100000 loops, best of 3: 8.96 µs per loop

For larger numbers, prime_list2 comes out the winner:

In [5]: %timeit prime_list(1000)
100 loops, best of 3: 8.28 ms per loop

In [6]: %timeit prime_list2(1000)
100 loops, best of 3: 2.46 ms per loop

In [7]: %timeit prime_list3(1000)
10 loops, best of 3: 23.5 ms per loop

In [11]: %timeit prime_list(10000)
1 loops, best of 3: 646 ms per loop

In [12]: %timeit prime_list2(10000)
10 loops, best of 3: 25.4 ms per loop

In [13]: %timeit prime_list3(10000)
1 loops, best of 3: 2.13 s per loop

OTHER TIPS

I can't figure out why you are using k

and your c should reset in "a" loop and out of "b" loop

code like this:

nums = []

for a in range(1, 11):
    c = 0
    for b in range(1, 11):
        if a % b == 0:
            c = c + 1
    if c == 2:
        nums.append(a)
print nums

I added two print statements to your code - first, under if a%b==0:, I added print a,b; and I print the final value of c after that loop. I get this output:

1 1
1
2 1
2 2
3
3 1
3 3
5
4 1
4 2
4 4
8
5 1
5 5
10
6 1
6 2
6 3
6 6
14
7 1
7 7
16
8 1
8 2
8 4
8 8
20
9 1
9 3
9 9
23
10 1
10 2
10 5
10 10
27

This tells you why you get nothing printed: after the b loop in a == 1, c is 1; after the same loop in the next iteration of the outer loop, c is now 3. So c==2 is never True when that test is made, so nums stays empty.

This also gives you a big hint as to what you need to do to fix it. c keeps increasing, but it should start counting afresh for each iteration of the outer loop - so, move your c=0 to be inside the outer for loop. You also need to change your final print loop to print d instead of print nums[d], or you will get another error. With those changes, your code looks like this:

nums = []                   
k=0
for a in range(1,11):          
    c=0
    for b in range(1,11):
        if a%b==0:
            c = c+1        
    if c == 2:                  
        nums.append(a)      
        k = k+1 
for d in nums:              
    print d

and it prints

2
3
5
7

as expected.

  1. Your c is not reset to zero inside the loop (the first loop). So set c=0 after line: for a in range(1,11):

  2. I dont know what your k is for. Is it usefull for anything?

  3. Printing the prime numbers dont do nums[d], print d. You are looping on the items not on the indices.

Your code has multiple issues - Every prime number is divisible by 1 so your checks will fail, you are printing nums[d] which is wrong, k is doing nothing, variable nomenclature is too obfuscated, you have unnecessary runs in for loop - you don't need to iterate for all values of b in range, it is sufficient to iterate over existing prime numbers and so on.

Here is how I would write it

primes = [2]
upper_limit = 1000 #find all primes < 1000

for candidate in range(2, upper_limit):
    can_be_prime = True
    for prime in primes:
        if candidate % prime == 0:
            can_be_prime = False
            break
    if can_be_prime:
        primes.append(candidate)

print primes

This solution is a little neater:

nums = []
for a in range(2, 101):
    for b in range(2, a):
        if a % b == 0:
            break
    else:
        nums.append(a)
print nums

Output:

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

Still, there is no point trying b > sqrt(a).

Try this:

nums = []                   
k=0
for a in range(2,11):          
    c=0
    for b in range(1,11):
        if a%b==0:          
            c = c+1      
    if c==2: 
        nums.append(a)      
        k = k+1
for d in nums:              
    print d

You will get

2
3
5
7

Note the code could be more efficient.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top