Prime Numbers
Finds every prime number up to a limit.
- Level
- Intermediate
- Topic:
- Math
- Concepts:
- Input & output
- Functions
- Mientras
- Para
- Math
Open in Codoritmo
Run, change and debug this example in your browser.
What you'll learn
The EsPrimo Funcion returns a Logico and uses MOD to look for divisors. Its Mientras loop stops early, past the square root or as soon as a divisor turns up.
Code
Funcion primo <- EsPrimo(n) Definir primo Como Logico Definir divisor Como Entero primo <- n > 1 divisor <- 2 // Basta con probar divisores hasta la raíz cuadrada de n Mientras primo Y divisor * divisor <= n Hacer Si n MOD divisor = 0 Entonces primo <- Falso FinSi divisor <- divisor + 1 FinMientrasFinFuncionAlgoritmo NumerosPrimos Definir limite, n, contador Como Entero Escribir "¿Hasta qué número busco primos?" Leer limite contador <- 0 Escribir "Primos hasta ", limite, ":" Para n <- 2 Hasta limite Hacer Si EsPrimo(n) Entonces Escribir Sin Saltar n, " " contador <- contador + 1 FinSi FinPara Escribir "" Escribir "Encontré ", contador, " números primos."FinAlgoritmoFlowchart
Each block in the flowchart matches one instruction in the code.
Sample run
This is what the program shows when it runs. The answers typed by the user are highlighted.
¿Hasta qué número busco primos?User answer: 50Primos hasta 50:2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 Encontré 15 números primos.
Complexity
How much work and memory it needs as the amount of data (n) grows.
| Case | Cost |
|---|---|
| Best | O(n√n) |
| Average | O(n√n) |
| Worst | O(n√n) |
| Memory | O(1) |
Challenge
Also show the sum of all the primes found.
Show hint
Add an accumulator to the Para loop in the main algorithm.
Related examples
Linear vs. Binary Search
Counts the comparisons each search needs on the same sorted list.
IntermediateCompound Interest
Watch your savings grow year by year.
IntermediateFibonacci Sequence
Prints the first terms of the Fibonacci sequence.
Beginner