Advertisement
newtonmark

Task 2 for prime number finding

Nov 30th, 2014
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.02 KB | None | 0 0
  1. object prime {
  2.  
  3.   def main (args: Array[String]) {
  4.  
  5.     val dataSet=(args(0).toInt to args(1).toInt) //generate a list of data from given range
  6.  
  7.     val primeList=dataSet.map(p=> // map those data to a prime data list
  8.     {
  9.       val dataSetSub=(2 to math.sqrt(p).toInt) // the sub data list is used to check whether a number is prime // In scala we normally use the val which is immuatable and we only use this list to do the interator
  10.       val resultList=dataSetSub.map(k=>
  11.       {
  12.         if(p%k==0) // if the number can be divided by the number ranging from 2 to its sqrt , that means this is not a prime
  13.           0
  14.         else
  15.           p
  16.       }
  17.       )
  18.       if(resultList.exists(p=>p==0)) // after the loop , if any data from the result result contains the 0 , which means this data is not a prime
  19.       {
  20.         0
  21.       }
  22.       else
  23.       {
  24.         p
  25.       }
  26.  
  27.     })//find prime
  28.    primeList.filter(p=>p!=0).map(println) // finally the prime data list will filter not 0 and left the prime number only.
  29.   }
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement