public
Last active

  • Download Gist
PrimeNumbers.scala
Scala
1 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
/**
* DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
* Version 2, December 2004
*
* Copyright (C) 2013 Lukáš Karas <lukas.karas@centrum.cz>
*
* Everyone is permitted to copy and distribute verbatim or modified
* copies of this license document, and changing it is allowed as long
* as the name is changed.
*
* DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
* TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
*
* 0. You just DO WHAT THE FUCK YOU WANT TO.
*/
 
/**
* This is a small useless example that prints prime numbers less that 1000, written in Scala.
*
* scalac PrimeNumbers.scala && java -classpath .:scala-library-2.9.2.jar PrimeNumbers
*/
object PrimeNumbers {
 
def primeTest(x: Stream[Int], y: Int): Boolean= {
if (x.isEmpty) {
true
} else {
//println(y + "%" + x.head )
if (y % x.head == 0) {
false
}
else {
primeTest(x.tail, y)
}
}
}
 
def isPrime2(i:Int ): Boolean = {
//println("is " + i + " prime?")
if (i!=2 && i%2==0)
false
else
primeTest((3 to (Math.sqrt(i).toInt) by 2).toStream, i)
}
 
 
def isPrime(i: Int): Boolean = {
if (i <= 3) {
true
} else {
 
if (i % 2 == 0) {
//println(i + " je sude cislo")
false
} else {
//println(i + " NENI sude cislo")
 
var sqrt = Math.sqrt(i).toInt
var j = 3
while (j <= sqrt) {
if (j == sqrt)
return true
else if (i % j == 0)
return false
j += 2
}
true
//throw new IllegalStateException("This should never happen")
 
}
}
}
 
def main(args: Array[String]) {
 
(1 to 1000).map(i => {
if (isPrime2(i))
println(i)
}
)
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.