Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- object prime {
- def main (args: Array[String]) {
- val dataSet=(args(0).toInt to args(1).toInt) //generate a list of data from given range
- val primeList=dataSet.map(p=> // map those data to a prime data list
- {
- 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
- val resultList=dataSetSub.map(k=>
- {
- 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
- 0
- else
- p
- }
- )
- 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
- {
- 0
- }
- else
- {
- p
- }
- })//find prime
- primeList.filter(p=>p!=0).map(println) // finally the prime data list will filter not 0 and left the prime number only.
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement