Count in factors: Difference between revisions

Content added Content deleted
(→‎{{header|Factor}}: edit whitespace, show all vocabs, style tweaks)
(→‎{{header|Scala}}: migrate to Scala 2.13)
Line 3,665: Line 3,665:


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>def primeFactors( n:Int ) = {
<lang scala>
object CountInFactors extends App {


def primeStream(s: Stream[Int]): Stream[Int] = {
def primeFactors(n: Int): List[Int] = {
s.head #:: primeStream(s.tail filter { _ % s.head != 0 })
}


val primes = primeStream(Stream.from(2))
def primeStream(s: LazyList[Int]): LazyList[Int] = {
s.head #:: primeStream(s.tail filter {
_ % s.head != 0
})
}

val primes = primeStream(LazyList.from(2))

def factors(n: Int): List[Int] = primes.takeWhile(_ <= n).find(n % _ == 0) match {
case None => Nil
case Some(p) => p :: factors(n / p)
}

if (n == 1) List(1) else factors(n)
}


// A little test...
def factors( n:Int ) : List[Int] = primes.takeWhile( _ <= n ).find( n % _ == 0 ) match {
{
case None => Nil
case Some(p) => p :: factors( n/p )
val nums = (1 to 12).toList :+ 2144 :+ 6358
nums.foreach(n => println("%6d : %s".format(n, primeFactors(n).mkString(" * "))))
}
}
if( n == 1 ) List(1) else factors(n)
}


// A little test...
{
val nums = (1 to 12).toList :+ 2144 :+ 6358
nums.foreach( n => println( "%6d : %s".format( n, primeFactors(n).mkString(" * ") ) ) )
}
}
</lang>
</lang>