write a programme to show the prime numbers between 1 to 20.

Dani AI

Generated

Direct answer for : the primes between 1 and 20 are 2, 3, 5, 7, 11, 13, 17, 19. Below are two small, ready-to-run Python examples: a simple trial-division checker (fine for tiny ranges) and a Sieve of Eratosthenes (better if you scale up). As suggested, know the rule first: 1 is not prime. 's prompt is noted.

Simple trial-division (easy to read and good for learning):

def is_prime(n):
    if n < 2:
        return False
    if n == 2:
        return True
    if n % 2 == 0:
        return False
    i = 3
    while i * i <= n:
        if n % i == 0:
            return False
        i += 2
    return True

primes = [p for p in range(1, 21) if is_prime(p)]
print(primes)  # [2, 3, 5, 7, 11, 13, 17, 19]

Sieve of Eratosthenes (fast when you need many primes):

def sieve(n):
    if n < 2:
        return []
    sieve = [True] * (n + 1)
    sieve[0] = sieve[1] = False
    for i in range(2, int(n**0.5) + 1):
        if sieve[i]:
            sieve[i*i:n+1:i] = [False] * (((n - i*i)//i) + 1)
    return [i for i, prime in enumerate(sieve) if prime]

print(sieve(20))  # [2, 3, 5, 7, 11, 13, 17, 19]

Notes and pitfalls: remember 1 is not prime; use range(1, 21) to include 20; trial division is O(n sqrt(n)), sieve is roughly O(n log log n). For learning, step through the trial function with a debugger or print statements to see why composite numbers fail the test.

Recommended Answers

All 2 Replies

You first.

First you must to know the pattern of prime number then u can write the code.
see wikipedia and FactMonster

commented: linkers +1
commented: N/A +1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.