Construct a program to read positive integer n and print all primes in the range [2, n]

Asked

Viewed 575 times

0

I need to create an algorithm that reads a number and tells you if it’s prime, and then print in a list all primes smaller than or equal to the read number.

I made an algorithm that says if you’re cousin or not, but I don’t know how to continue...

n = int(input("Verificar numeros primos ate: "))
mult=0

for count in range(2,n):
    if (n % count == 0):
        print("Múltiplo de",count)
        mult += 1

if(mult==0):
    print("É primo")
else:
    print("Tem",mult," múltiplos acima de 2 e abaixo de",n)

3 answers

5

Since you already have the main part of the code ready, I will put here a pseudo-code of how it could continue, considering that you already have a function called é_primo returning True or False.

número = leia("Informe um número:")

se é_primo(número)
  escreva("Número informado é primo")
senão
  escreva("Número informado não é primo")

enquanto número > 0
  número = número - 1
  se é_primo(número)
    escreva("O número", número, "também é primo")

So you will be checking the number informed and displaying all the smaller cousins that it.

2

Faced with a practical situation and aiming at a better efficiency of the code it would be interesting to organize the logic of the question as follows:

  1. Capture the value of n;
  2. Calculate all the prime numbers which were greater than or equal to "2" and less than or equal to "n".

With this logic I implemented the following code:

def exibir_primos(n):
    li = 2
    numeros_primos = list()
    while li <= n:
        if primo(li):
            numeros_primos.append(li)
        li += 1
    return numeros_primos


def primo(m):
    i = 1
    cont = 0
    while i <= m:
        if m % i == 0:
            cont += 1
        i += 1
    if cont != 2:
        return False
    else:
        return True


num = int(input('Digite um número inteiro: '))

print(f'\033[32mOs números primos entre "2" e "{num}" são:\n{exibir_primos(num)}')

See here the functioning of the code.

Note that when we execute this code we receive the following message: Digite um número inteiro: . Right now we must enter an integer number.

Later this value is sent to function exibir_primos(). From this moment the block while shall travel through the closed interval [2, n] and, with the aid of the block if, will be verified whether each element, of the respective interaction, is in fact a number cousin. So the block if will ask the function primo() if the value li is in fact a prime number. At this time the funcao() shall calculate the amount of li. If this amount is equal to 2, the function exibir_primos receive from the function primo() the value True. Otherwise, the function exibir_primos will receive the value False.

If the function returns primo() be it False, the for of function exibir_primos end the respective interaction and start the next one. If the function returns primo() be it True, the value that has been confirmed as prime will be added to the list numeros_primos.

This verification will be performed to each of the numbers who are in the closed interval [2, n]. After you have completed these checks, the function return - which in this case is the list numeros_primos - will be shown.

Example:

Imagine we wish to know which prime numbers are greater or equal to 2 and less than or equal to 26.

At the time of execution of the code we received the message: Digite um número inteiro: . Right now we must type...

26

...and press enter.

From now on the code will perform all the work and show us the following output:

Os números primos entre "2" e "26" são:
[2, 3, 5, 7, 11, 13, 17, 19, 23]

Note that the program will display all prime numbers greater than or equal to "2" and less than or equal to "26".

Observing:

The numbers 24, 25 and 26 were not displayed in the list - as were other numbers - because they were not prime.

  • what is that /033 in the print(f)? What does he do?

  • 1

    @Yoyo, the \033 is an octal code that serves as an escape character ANSI.

0

The ideal would be to separate the task into two functions, one that receives a number n and returns True if he is cousin and False otherwise; and another function that also receives the same number n, but return a list with all prime numbers up to n. Then, if you want to create an interaction with the user, something like a print('O número selecionado é primo!'), do this out of the two functions or create another especially for this purpose.

In my case, the function checkPrimo() is the one that will return True or False to a specific number. The function that will generate the list I will call listador().

def listador():
    
    primos = [] # Crie uma lista vazia primeiro, nesta serão implementados os números primos.

    for numero in range(2, n): # posso começar o range() com 2, porque 0 e 1 já se sabe que não são primos.

        if checkPrimo(numero) == True: # Caso a condição seja verdadeira, ou seja, o número seja primo, o bloco será executado. O fragmento "== True" é facultativo.
            primos.append(numero) # Isto adicionará 'numero' à lista 'primos'.

    return primos # Por fim, retorna-se a lista para que esta função possa ser encadeada dentro de outras funções com mais praticidade.

It is worth remembering that range(2, n) will never add n within the list, this because the last iteration of range() always is "n-1". If you wish to add it to the list, simply switch to range(2, n + 1).

The last line, the one that returns the list primos, is optional; it is up to you to write it or not. Even if it is not returned, it will still be available outside the function after it has been executed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.