How to get first 100 prime numbers in scala as i got result but it dispays blank where it's not found

后端 未结 3 1297
不思量自难忘°
不思量自难忘° 2021-01-28 18:14

output : prime numbers 2 3 () 5 () 7 () ()

i want as 2 3 5 7

def primeNumber(range: Int): Unit ={

    val primeNumbers: immutable.IndexedSeq[AnyVal] =
         


        
3条回答
  •  暖寄归人
    2021-01-28 18:41

    The reason is if else returning two types of value one is prime value and another is empty. You could return 0 in else case and filter it before printing it.

    scala> def primeNumber(range: Int): Unit ={
         | 
         |     val primeNumbers: IndexedSeq[Int] =
         | 
         |       for (number :Int <- 2 to range) yield{
         | 
         |         var isPrime = true
         | 
         |         for(checker : Int <- 2 to Math.sqrt(number).toInt if number%checker==0 if isPrime) isPrime = false
         | 
         |         if(isPrime)  number
         |         else 
         |         0
         |       }
         | 
         |     println("prime numbers" + primeNumbers)
         |     for(prime <- primeNumbers.filter(_ > 0))
         |        println(prime)
         |  }
    primeNumber: (range: Int)Unit
    
    scala> primeNumber(10)
    prime numbersVector(2, 3, 0, 5, 0, 7, 0, 0, 0)
    2
    3
    5
    7
    

    But we should not write the code the way you have written it. You are using mutable variables. Try to write code in an immutable way. For example

    scala> def isPrime(number: Int) =
         | number > 1 && !(2 to number - 1).exists(e => e % number == 0)
    isPrime: (number: Int)Boolean
    
    scala> def generatePrimes(starting: Int): Stream[Int] = {
         | if(isPrime(starting))
         | starting #:: generatePrimes(starting + 1)
         |  else
         | generatePrimes(starting + 1)
         | }
    generatePrimes: (starting: Int)Stream[Int]
    
    scala> generatePrimes(2).take(100).toList
    res12: List[Int] = List(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101)
    

提交回复
热议问题