No tienes acceso a esta clase

隆Contin煤a aprendiendo! 脷nete y comienza a potenciar tu carrera

Adquiere por un a帽o todos los cursos, escuelas y certificados por un precio especial.

Antes: $249

Currency
$219/a帽o

Paga en 4 cuotas sin intereses

Paga en 4 cuotas sin intereses
Comprar ahora

Termina en:

1D
11H
29M
24S

Ciclo while

23/33
Recursos

Aportes 55

Preguntas 0

Ordenar por:

驴Quieres ver m谩s aportes, preguntas y respuestas de la comunidad?

o inicia sesi贸n.

let endNumber = 100
var startNumber = 2
var primeNumbers:[Int] = []
while startNumber <= 100 {
    var isPrime = true
    for idx in 2..<startNumber {
        if startNumber % idx == 0 {
            if idx != 1 && idx != startNumber {
                isPrime = false
            }
        }
    }
    if isPrime {
        primeNumbers.append(startNumber)
    }
    startNumber += 1
}

Mi MacBook Pro i7 no pudo acabar el ciclo en menos de 3 minutos 馃槀

import UIKit

func isPrime(n: UInt64) -> Bool {
    if n == 0 { return false }
    if n == 1 { return false }
    var found = false
    var min: UInt64 = 2 // Primer posible divisor
    let max: UInt64 = UInt64(n / 2) // Matematicamente esta demostrado que si no existe hasta n / 2 no existe divisor \LOL
    while min <= max && !found {
        found = n % min == 0
        min += 1
    }
    
    return !found
}


for n in 0...100000 {
    if isPrime(n: UInt64(n)) {
        print("\(n)", terminator: " ")
    }
}
let ini = 2
let fin = 100
var prime : [Int] = []

for i in ini...fin {
    var isPrime = true
    for j in ini..<i {
        if i % j == 0{
            isPrime = false
        }
    }
    if isPrime{
        prime.append(i)
    }
}

Les dejo la informaci贸n a continuaci贸n, vale la pena darnos una vuelta y leer esto 馃槺

https://es.wikipedia.org/wiki/Criba_de_Erat贸stenes

Mi soluci贸n

var numStart = 2
var mult = 1
var count = 0
while numStart <= 100 {
    while mult <= numStart {
        if (numStart % mult) == 0 {
            count += 1
        }
        mult += 1
    }
    if count <= 2 {
        print("\(numStart) es un n煤mero primo")
    }
    numStart += 1
    mult = 1
    count = 0
}

// Reto
var numbers = Set<Int>()
var criba = Set<Int>()

for totalNumbers in 1...100 {
    numbers.insert(totalNumbers)
}
criba.insert(1)
for multiplesOf2 in stride(from: 4, to: 101, by: 2){
    criba.insert(multiplesOf2)
}
for multiplesOf3 in stride(from: 6, to: 101, by: 3){
    criba.insert(multiplesOf3)
}
for multiplesOf5 in stride(from: 10, to: 101, by: 5){
    criba.insert(multiplesOf5)
}
for multiplesOf7 in stride(from: 14, to: 101, by: 7){
    criba.insert(multiplesOf7)
}

let primeNumbers = numbers.symmetricDifference(criba).sorted()
print(primeNumbers)

Naive Algorithm

//Ejercicio - N煤mero primos del 2 al 100
let n = 100
var number = 2 //From number to 100
var div = 2 //First prime number, first divisor for all numbers from now on.

while number <= n
{
    var isPrime = true //Let's assume number is always prime until we demonstrate the opposite
    while (isPrime) && (number != div)
    {
        isPrime = ( number % div != 0 )
        div += 1
    }
    div = 2 //Reset div to 2 to iterate for the next loop
    if isPrime
    {
        print(number, separator: "", terminator: " ") //Wanna know which ones are primes
    }
    number += 1 //Next number
}
//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 
var min = 2
var max = 100
var noPrimos = Set<Int>()
print("Los numeros primos en el rango 2 a 100: ", terminator: " ")
while min < max {
    for aux in (min+1)...max {
        if aux%min == 0 {
            noPrimos.insert(aux)
        }
    }
    if !noPrimos.contains(min) {
        print("\(min),", terminator: " ")
    }
    min += 1
}

Siguiendo el algoritmo de la criba de Erat贸stenes (rayando), mi soluci贸n queda de la siguiente forma:

https://es.wikipedia.org/wiki/Criba_de_Erat贸stenes

// MARK: Eratosthenes' sieve
let a = 2
let b = 100
var sieve: [Int] = Array(a...b)

var j = 0
while j < sieve.count {
    let value = sieve[j]
    
    if value * value >= b {
        break
    }
    
    var k = j + 1
    while k < sieve.count {
        if sieve[k] % value == 0 {
            sieve.remove(at: k)
        } else {
            k += 1
        }
    }
    
    j += 1
}
sieve

//Esta es mi soluci贸n
for i in 1鈥100 {

if i == 2 || i == 3 {
    print("El numero \(i) es numero primo")

}

var isPrime = false


if (i % 2) != 0 {
    
    var Mid = (i-1)/2
    
    var Counter = 2
                                         
    while (!isPrime) && (Counter <= Mid){
                    
        if Counter == Mid{
            print("El n煤mero \(i) es n煤mero primo")
            
        }
        if (i % Counter) == 0 {
            isPrime = true
            
        }
        Counter += 1
    }
                               
}

}

Reto:

var contador = 0
while contador <= 10 {
contador += 1
}
print(contador)

repeat{
contador += 1
}while contador <= 0
print(contador)

//ejercicio tomar un numero del 2 al 100 y localizar el numero primo.

let numerPrime = 100
var startNumber = 2
var primeNumers:[Int] = []
while startNumber <= 100 {
var isPrime = true
for divisor in 2鈥<startNumber {
if startNumber % divisor == 0{
if divisor != 1 && divisor !=
startNumber {
isPrime = false
}
}
}
if isPrime {

primeNumers.append(startNumber)
}
startNumber += 1

}
print(primeNumers)

// Ejercicio entre 1 y 100 cuales son los n煤meros primos
var numerosPrimos: [Int] = []

for numeroInicial in 2...100 {
    var esPrimo = true
    for divisor in 2..<numeroInicial {
        if numeroInicial % divisor == 0 {
            esPrimo = false
            break
        }
    }
    if esPrimo {
        numerosPrimos.append(numeroInicial)
    }
}
numerosPrimos
//Reto
var number = 1
var divisionCount = 0
var primeNumbers = [Int]()

while number < 100{
    for i in 1...number{
        if number%i == 0 {
            divisionCount += 1
        }
    }
    if divisionCount == 2 {
        primeNumbers.append(number)
    }
    number += 1
    divisionCount = 0
}

primeNumbers

//EJERCICIOS

for i in 2...100 {
    var esPrimo = true
    
    for j in 2..<i {
        if i % j == 0 {
            esPrimo = false
            break
        }
    }
    
    if esPrimo {
        print(i)
    }
}
let max:Int = 100
var i:Int = 0
var j:Int = 0
var count:Int = 0

while i < max {
    i += 1
    j = 0
    count = 0
    
    while j < i && count <= 2 {
        j += 1
        if(i % j == 0) {
           count += 1
        }
    }

    if (count == 2) {
        print(i, terminator: " ")
    }
}
var num : Int = 1000

func isPrime(n: Int) -> Bool{
	if [0,1].contains(n){
   	 return false
	} 

	if n == 2 {return true}

  for i in 2...(n - 1){
     if n % i == 0{
        return false
     }
  }

  return true
}

for i in 0...num{
   if isPrime(n : i){
     print("Numero \(i) es primo")
   }
}

Reto obtener los numeros primos 0 - 100



var primeNumbers: Set<Int> = []
var noPrimeNumbers: Set<Int> = []
var operationSet: Set<Int> = []
let startNumber = 2
let endNumber = 100

for i in startNumber...endNumber{
      
    for j in startNumber...endNumber{
        if (i % j == 0) && (j != 1) && (i != j)  {
            //print(i)
            noPrimeNumbers.insert(i)
            break
        }
    }
}
//print(noPrimeNumbers)

for idx in startNumber...endNumber{
    operationSet.insert(idx)
}
//print(operationArray)
primeNumbers = operationSet.subtracting(noPrimeNumbers)

print(primeNumbers.sorted())
 
var primesNumbers: [UInt8] = []
let maxNumbers: UInt8 = 100
var primesCounter: UInt8 = 2

while primesCounter <= maxNumbers {
    var numbersCollector: [UInt8] = []
    var bucleCounter: UInt8 = 2
    
    while  bucleCounter <= maxNumbers {
        if primesCounter % bucleCounter == 0 {
            numbersCollector.append(primesCounter)
        }
        bucleCounter += 1
    }
    
    if numbersCollector.count == 1 {
        primesNumbers.append(primesCounter)
    }
    numbersCollector = []
    bucleCounter = 2
    primesCounter += 1
}

primesNumbers

Con una tupla

let range = (from: 2, to: 100)
var primeNumbers : Set<Int> = []

for i in range.from...range.to {
    var isPrime = true
    for j in range.from..<i {
        if i % j == 0{
            isPrime = false
        }
    }
    if isPrime { primeNumbers.insert(i) }
}
print(primeNumbers.sorted())
for i in 2...100 {
    if isPrime(number: i) {
        print("Numero primo: \(i)")
    }
}

func isPrime(number: Int) -> Bool {
    for i in 2..<number {
        if number%i == 0 {
            return false
        }
    }
    return true
}

let start = 1
let finish = 100
var prime : [Int] = []
var numberOfDivisors = 0

for i in start...finish {
    for j in start...i {
            if i % j == 0 {
                numberOfDivisors+=1
            }
        }
    if numberOfDivisors == 2 {
        prime.append(i)
    }
    numberOfDivisors = 0
}

Realice el ejercicio y lo quise hacer un poco mas complejo devolviendo tambien los que son no primos, llegue hasta aqui, pero esta mal, como podria arreglarlo?
siento que hice una ensalada jaja

let endNumber = 100
var startNumber = 2
var primeNumbers:[Int] = []
var noPrimeNumbers: [Int] = []
while startNumber <= 100 {
    var isPrime = true
    var noPRime = false
    for idx in 2..<startNumber {
        if startNumber % idx == 0 {
            if idx != 1 && idx != startNumber {
                isPrime = false
            } else if (startNumber != 0) && idx != 0 {
                if (idx != 0) startNumber
                    noPRime = true
            }
        }
    }
    if isPrime {
        primeNumbers.append(startNumber)
    }
    else if noPrime {
        noPrimeNumbers.append(startNumber)
    }
    startNumber += 1
}
var starNumber = 1
let numberMaxim = 100
var numberPrime = [Int]()
var numberDivisible = 0

while(starNumber <= numberMaxim){
    if(starNumber % 1 == 0)
    {
      numberDivisible += 1
    }
    if(starNumber != 1)
    {
        for var isNumberDivisible in 2...starNumber{
            if(starNumber % isNumberDivisible == 0)
            {
                numberDivisible += 1
            }
            if(isNumberDivisible == starNumber && numberDivisible == 2)
            {
                numberPrime.append(starNumber);
            }
            if(numberDivisible > 2)
            {
                isNumberDivisible = starNumber
            }
        }
    
    }
    numberDivisible=0;
    starNumber += 1
}
print(numberPrime)
var initialNumber = 2

while initialNumber <= 100 {
    var isPrime = true
    var divisor = 2
    while divisor < initialNumber {
        if initialNumber % divisor == 0 {
            isPrime = false
            break
        }
        divisor += 1
    }
    if isPrime {
        print(initialNumber)
    }
    initialNumber += 1
}```

var numero : UInt8 = 2
var primo : [UInt8] = [UInt8]()
var I : UInt8
var Count : UInt8

for _ in 1...100{
    I = 1
    Count = 0
    while I <= numero{
        if numero%I == 0 {
            Count += 1
        }
        I += 1
    }
    if Count > 2 {
        numero += 1
    } else {
        primo.append(numero)
        numero += 1
    }
}

print(primo)

let begin = 2
let fin = 100

for x in begin...fin {
    var isPrime = true
    for y in begin..<x{
        if x % y == 0{
            isPrime = false
        }
    }
    if isPrime {
        print(x)
    }
}
var a = 0, b = 1, c = 0

for a in 1 ... 100 {
    b = 1
    c = 0
    while b <= a {
        if a % b == 0 {
            c = c + 1
        }
        b += 1
    }
    if c == 2 {
        print(a)
    }
}
print("----------------------------")
print("Prime numbers")
print("----------------------------")
var number = 0
let maxNumber = 100

func is_prime(n: Int) -> Bool {
    if n <= 1 {
        return false
    }
    if n <= 3 {
        return true
    }
    var i = 2
    while i*i <= n {
        if n % i == 0 {
            return false
        }
        i = i + 1
    }
    return true
}

repeat {
    if is_prime(n: number) {
        print("\(number) is a prime number.")
    }
    number += 1
} while(number <= maxNumber)

let primo = 3
var contador = 0

for i in 1鈥rimo{
if(primo % i == 0){
contador += 1
}
}

if(contador == 2){
print(鈥渆l n煤mero es primo鈥)
}else{
print(鈥渆l n煤mero no es primo鈥)
}

Mi soluci贸n al reto:

for i in 2...100 {
    if !(2...i).contains(where: { i.isMultiple(of: $0) && ($0 != 1 && $0 != i) }) {
        print("\(i) es primo.")
    }
}

He utilizado un m茅todo propio de las colecciones como es .contains, que ser谩 el encargado de buscar internamente aquellos n煤meros comprendidos en el rango indicado que cumplan la condici贸n del where.

En esa condici贸n, buscamos que el m煤ltiplo del n煤mero buscado sea 1 y el n煤mero de la iteraci贸n correspondiente.

el repeat while hereda de Objective-C. Esta estructura de control antes era el do-while.

un ejemplo usando while, break e if:

// bucle while:
var contador = 1
while true{
    contador += 1
    print("Hi!")
    if contador == 5{
        break
    }
}

Comparto mi c贸digo para obtener los n煤meros primos para el rango del 1 al 100

import UIKit

var primeNumbers : [Int] = []
for idx in 1...100 {
    if idx > 1 {
        if idx == 2
        {
            primeNumbers.append( idx )
        }
        else
        {
            var isPrime : Bool = true
            var divisor = 3
            repeat {
                if(idx%2 == 0)
                {
                    isPrime = false
                }
                else
                {
                    if( divisor%2 != 0)
                    {
                        if( idx%divisor == 0 && idx != divisor)
                        {
                            isPrime = false
                        }
                    }
                    
                    divisor += 1
                }
                
            } while(isPrime && divisor<idx)
            
            if isPrime {
                primeNumbers.append( idx )
            }
        }
            
    }
}

var strPrimeNumbers : String = ""
for primeNumber in primeNumbers {
    if strPrimeNumbers.isEmpty
    {
        strPrimeNumbers = String( primeNumber )
    }
    else
    {
        strPrimeNumbers += "," + String( primeNumber )
    }
        
}

print("Los n煤meros primos para el rango del 1 al 100 son : \( strPrimeNumbers )")
    
        

Este es mi c贸digo

let lastNumber : Int = 100;
let firstNumber : Int = 2;
for currentNumber in firstNumber...lastNumber{
    var isPrime : Bool = true;
    for y in 2..<currentNumber{
        if currentNumber % y == 0{
            isPrime = false;
        }
    }
    if isPrime {
        print("El numero \(currentNumber) es primo")
    }
}

Estaba teniendo un problema que dec铆a : Can鈥檛 perform range with end < start"
lo que hice fue cambiar firstNumber鈥<currentNumber por stride(from: firstNumber, to: currentNumber, by: 1) y se solucion贸, tiempo despu茅s haciendo pruebas lo volv铆 a poner como firstNumber鈥<currentNumber y ya no me dio el error, si alguien sabe que pas贸 ser铆a excelente

var number = 0
main: while number < 100{
    number += 1
    var retro = 0
    while retro < number{
        retro += 1
        if number%retro == 0 && retro != 1 && number != retro {
            continue main
        }
    }
    print(number)
}
var primeNumbers = [Int]()
var initialNum = 2
var equealTimes = 0

while initialNum <= 100 {
    equealTimes = 0
    for num in 1...initialNum {
        if initialNum % num == 0 {
            equealTimes+=1
        }
        if equealTimes == 2 && num == initialNum {
            primeNumbers.append(num)
        }
    }
    initialNum+=1
}

print(primeNumbers)



var limit = 100
var n = 2
while n <= limit{
    if n == 2{
        print("valor 2 es primo")
    }else{
        var amount = 0
        for i in 2...n-1{
            if n.isMultiple(of: i) {
                amount += 1
            }
        }
        
        print("valor \(n) "+(amount>0 ? "no es" : "es")+" primo")
        
        
    }
    n += 1
}
//reto
var initialValue = 2
let finalValue = 100
var primes: [Int] = []


for i in initialValue...finalValue {
    var prime = true
    for n in initialValue..<i {
        if i % n == 0 {
            prime = false
        }
    }
    if prime {
        primes.append(i)
    }
}
for i in primes {
    print("el numero \(i) es primo ")
}

//Ejercicio: Del 1 al 100, buscar los numros primos
i = 1
let maxNumber = 100
var primo = false

while i <= maxNumber{
primo = false
for j in 1鈥100{
if (j != 1) && (j != i){
if i % j == 0{
primo = true
}
}
}
if primo == false {
print(鈥淣umero primo: (i)鈥)
}
i += 1
}

As铆 qued贸 mi ejercicio:

let n = 100
var sieve = Set<Int>()
var multiples = Set<Int>()
for i in 2...n {
    if !multiples.contains(i) {
        for j in stride(from: i*i, to: n+1, by: i) {
            multiples.insert(j)
        }
        sieve.insert(i)
    }
    multiples.remove(i)
}
print(sieve.sorted())
var countPrime = 0
for num in 2...100{
    for idx in 1...num{
        if num % idx == 0{
            countPrime += 1
        }
    }
    if countPrime <= 2{
        print(num)
    }else{
        countPrime = 0
    }
}

馃憤

<import UIKit

var numerosPrimos = [Int8]()
var numero: Int8 = 1

while numero <= 100 {
    var esPrimo = true
    if numero != 1{
        for dividendo in 1..<numero {
            if numero % dividendo == 0 && dividendo != 1 {
                esPrimo = false
                break
            }
        }
        if esPrimo {
            numerosPrimos.append(numero)
        }
    }
    numero += 1
}

for numeroPrimo in numerosPrimos {
    print(numeroPrimo)
}>

var primeNumbers = Int
var number = 2

while number <= 100 {
var isPrime = true
for divisor in 2鈥<number{
if number % divisor == 0 && divisor != 1{
isPrime = false
break
}
}
if isPrime {
primeNumbers.append(number)
}
number += 1
}

print(primeNumbers)

// Numeros primos

for num in 2...100 {
    let number = num
    var increment = 1
    var counter = 0
    while increment <= number {
        if number % increment == 0 {
            counter += 1
        }
        increment += 1
    }
    
    if counter == 2 {
        print("El n煤mero \(number) es primo")
    }
}

Repeat - while, hace lo que en otros lenguajes se hace con Do-while.

Criba de Erat贸stenes, los n煤meros de color rojo son los primos.

var listOfPrimeNumber : [Int] = []
let lastNumber = 100
var numberToKnow = 1

repeat {
//    var comparateNumber = numberToKnow
    var isPrime = true
    for number in 1...lastNumber {
        if numberToKnow % number == 0 {
            if number != 1 && number != numberToKnow {
                isPrime = false
            }
        }
    }
    if isPrime == true {
        listOfPrimeNumber.append(numberToKnow)
    }
    numberToKnow = numberToKnow + 1
    
}while numberToKnow <= lastNumber
listOfPrimeNumber

![](

for idx in 2...100 {
    var prime = true
    var min = 2
    while min < idx {
        if idx % min == 0{
            prime = false
            break
        }
        min += 1
    }
    prime ? print("\(idx) is prime     鉁") : print("\(idx) is not prime 鉂")
}
for number in 1...100 {
    var counter = 2
    var isPrime = true
    while counter < number {
        if number % counter == 0 {
            isPrime = false
            break
        }
        counter += 1
    }
    if isPrime {
        print("The number \(number) is prime")
    }
}