Rich Ashworth
Rich Ashworth

Reputation: 2015

A function to determine whether one number is a factor of another in an argument to foldLeft in Scala

I am trying to define a function in Scala to determine whether a number is prime as follows:

def isPrime(n: Int): Boolean = {
   if (n == 2) true
   else {
      List(3 to math.sqrt(n)).foldLeft(isFactor(),0)
   }
   def isFactor(x:Int, n:Int):Boolean=(n%x)==0
}

What arguments to give to the foldLeft call, given that I have already defined isFactor?

Upvotes: 0

Views: 148

Answers (2)

Rich Ashworth
Rich Ashworth

Reputation: 2015

thanks to advice from @thoredge, I've been able to do this using exists() as follows:

def isPrime(n: Int): Boolean = n match {
  case 2 => true
  case _ => !(2 to math.sqrt(n).ceil.toInt).exists((x) => n % x == 0)
}

Upvotes: 0

thoredge
thoredge

Reputation: 12601

I guess you want to find if any of the items in the list is a factor of n. So for an empty list you should then start with false, since an empty list holds no factors of n. However, you'll have to keep comparing the collected result with the isFactor result. The simplest of course with be to check out the list.exists(...)-method.

Upvotes: 2

Related Questions