Check if number is prime in O(sqrt(n)) in Scala - scala

When checking if n is a prime number in Scala, the most common solutions is concise one-liner which can be seen in almost all similar questions on SO
def isPrime1(n: Int) = (n > 1) && ((2 until n) forall (n % _ != 0))
Moving on, it's simple to rewrite it to check only odd numbers
def isPrime2(n: Int): Boolean = {
if (n < 2) return false
if (n == 2) return true
if (n % 2 == 0) false
else (3 until n by 2) forall (n % _ != 0)
}
However, to be more efficient I would like to combine checking only odds with counting up to sqrt(n), but without using Math.sqrt. So, as i < sqrt(n) <==> i * i < n, I would write C-like loop:
def isPrime3(n: Int): Boolean = {
if (n < 2) return false
if (n == 2) return true
if (n % 2 == 0) return false
var i = 3
while (i * i <= n) {
if (n % i == 0) return false
i += 2
}
true
}
The questions are:
1) How to achieve the last version in the first version nice Scala functional style?
2) How can I use Scala for to this? I thought of something similar to below, but don't know how.
for {
i <- 3 until n by 2
if i * i <= n
} { ??? }

Here is a method to verify if n is prime until sqrt(n) without using sqrt:
def isPrime3(n: Int): Boolean = {
if (n == 2) {
true
} else if (n < 2 || n % 2 == 0) {
false
} else {
Stream.from(3, 2).takeWhile(i => i * i < n + 1).forall(i => n % i != 0)
}
}
If you want to do it until n/2, which is also a possible optimization (worse than sqrt(n)), you can replace the last line with:
(3 to n/2 + 1 by 2).forall(i => n % i != 0)
If you prefer, you could also make a tail recursive version, something along these lines:
import scala.annotation.tailrec
def isPrime3(n: Int): Boolean = {
if (n == 2 || n == 3) {
true
} else if (n < 2 || n % 2 == 0) {
false
} else {
isPrime3Rec(n, 3)
}
}
#tailrec
def isPrime3Rec(n:Int, i: Int): Boolean = {
(n % i != 0) && ((i * i > n) || isPrime3Rec(n, i + 2))
}

Related

Facing Issues in Recursion of Perfect Number Problem

I've been working on the scala recursion problem. I used to develop the program using loops and then use the concept of recursion to convert the existing loop problem in a recursive solution.
So I have written the following code to find the perfect number using loops.
def isPerfect(n: Int): Boolean = {
var sum = 1
// Find all divisors and add them
var i = 2
while ( {
i * i <= n
}) {
if (n % i == 0) if (i * i != n) sum = sum + i + n / i
else sum = sum + i
i += 1
}
// If sum of divisors is equal to
// n, then n is a perfect number
if (sum == n && n != 1) return true
false
}
Here is my attempt to convert it into a recursive solution. But I'm getting the incorrect result.
def isPerfect(n: Int): Boolean = {
var sum = 1
// Find all divisors and add them
var i = 2
def loop(i:Int, n:Int): Any ={
if(n%i == 0) if (i * i != n) return sum + i + n / i
else
return loop(i+1, sum+i)
}
val sum_ = loop(2, n)
// If sum of divisors is equal to
// n, then n is a perfect number
if (sum_ == n && n != 1) return true
false
}
Thank you in advance.
Here is a tail-recursive solution
def isPerfectNumber(n: Int): Boolean = {
#tailrec def loop(d: Int, acc: List[Int]): List[Int] = {
if (d == 1) 1 :: acc
else if (n % d == 0) loop(d - 1, d :: acc)
else loop(d - 1, acc)
}
loop(n-1, Nil).sum == n
}
As a side-note, functions that have side-effects such as state mutation scoped locally are still considered pure functions as long as the mutation is not visible externally, hence having while loops in such functions might be acceptable.

fast power function in scala

I tried to write a function for fast power in scala, but I keep getting java.lang.StackOverflowError. I think it has something to do with two slashes that use in the third line when I recursively called this function for n/2.
Can someone explain why is this happening
def fast_power(x:Double, n:Int):Double = {
if(n % 2 == 0 && n > 1)
fast_power(x, n/2) * fast_power(x, n /2)
else if(n % 2 == 1 && n > 1)
x * fast_power(x, n - 1)
else if(n == 0) 1
else 1 / fast_power(x, n)
}
Your code doesn't terminate, because there was no case for n = 1.
Moreover, your fast_power has linear runtime.
If you write it down like this instead:
def fast_power(x:Double, n:Int):Double = {
if(n < 0) {
1 / fast_power(x, -n)
} else if (n == 0) {
1.0
} else if (n == 1) {
x
} else if (n % 2 == 0) {
val s = fast_power(x, n / 2)
s * s
} else {
val s = fast_power(x, n / 2)
x * s * s
}
}
then it is immediately obvious that the runtime is logarithmic, because
n is at least halved in every recursive invocation.
I don't have any strong opinions on if-vs-match, so I just sorted all the cases in ascending order.
Prefer the match construct instead of multiple if/else blocks. This will help you isolate the problem you have (wrong recursive call), and write more understandable recursive functions. Always put the termination conditions first.
def fastPower(x:Double, m:Int):Double = m match {
case 0 => 1
case 1 => x
case n if n%2 == 0 => fastPower(x, n/2) * fastPower(x, n/2)
case n => x * fastPower(x, n - 1)
}

Scala Error: identifier expected but '}' found

I'm trying to figure out this compile error:
Error:(51, 4) identifier expected but '}' found.
} else if (n < 0) {
^
For this code:
def nthPowerOfX(n: Int, x:Double) : Double = {
if (n == 0) {
1.0
} else if (n < 0) {
1.0 / nthPowerOfX(n,x)
} else if (n % 2 == 0 && n > 0) {
nthPowerOfX(2, nthPowerOfX(n/2,x))
} else {
x*nthPowerOfX(n-1, x)
}
}
I tried return statements too but that didn't help nor should it matter to my understanding.
Jozef is right! There is no error. Please consider using this:
def nthPowerOfX(n: Int, x:Double) : Double = {
n match{
case 0 => 1.0
case x if x < 0 => 1.0 / nthPowerOfX(n,x)
case x if x % 2 == 0 && x > 0 => nthPowerOfX(2, nthPowerOfX(n/2,x))
case x => x*nthPowerOfX(n-1, x)
}
}
But keep in mind that recursion is dangerous thing, it's better to use tail recursion, if we are talking about Scala.

Parenthesis Balancing in Scala

Here is my problem: I don't understand how the code works.
How does "())(" return false?
def balance(chars: List[Char], numOpens: Int): Boolean = {
if (chars.isEmpty) {
numOpens == 0
} else {
val h = chars.head
val n =
if (h == '(') numOpens + 1
else if (h == ')') numOpens - 1
else numOpens
if (n >= 0) balance(chars.tail, n)
else false
}
}
The lines:
if (n >= 0) balance(chars.tail, n)
else false
mean that if at any point there are any unbalanced ) characters, false will be returned immediately (n will be < 0). For the specific example you give: ())( we can follow how the value of n varies as the function works through the string:
First character - (: n -> 1, continue check using remaining characters: ))(
Second character - ): n -> 0, continue check using remaining characters: )(
Third character - ): n -> -1, else triggered - return false immediately. The fourth character is never checked.
Shadowlands's answer is correct, but I hope you'll find this more demonstrative:
Let's imagine we are on the top upper stair of infinite stairway. And there is an instruction: ( means step down (↓), ) means step up (↑) and you should ignore all other instructions.
val n =
if (h == '(') numOpens + 1 // step down
else if (h == ')') numOpens - 1 // step up
else numOpens // ignore
After the last step we have to stand on the top upper stair. Otherwise instruction is invalid.
if (chars.isEmpty) {
numOpens == 0
} else { ... }
You can't make a step up from the top upper stair, otherwise instruction is invalid.
if (n >= 0) ...
else false // there is no stairs upper than the upper one (0)
Example:
())( means ↓↑↑↓. After this part ↓↑ you'll be on the top upper stair, so you can't make step up after next command (↑) (n < 0), so the instruction is invalid.

How to get unique elements from two lists of strings in scala?

I have two list to compare:
List one:
List("one","two","three","four")
List two:
List("one","two")
how can I get the unique values from these two lists?
If your two lists are r1 and r2, and assuming you want the values in each list that are not present in the other:
r1.filterNot(r2.contains) ::: r2.filterNot(r1.contains)
or
r1.diff(r2) ::: r2.diff(r1)
Turn them into sets, and get the intersection. You may then turn it back to Seq if you want, but first ask yourself if they had to be Seq in first place, instead of Set.
scala> List("one","two","three","four").toSet & List("one","two").toSet
res0: scala.collection.immutable.Set[String] = Set(one, two)
Use The difference operator for Set &~
http://www.scala-lang.org/api/current/scala/collection/immutable/Set.html
I use List(1, 2, 3, 4) ::: List(1, 2, 5) distinct for this issue. It returns List(1, 2, 3, 4, 5).
I would suggest using the following for O(m+n) running time (assumes input arrays are sorted).
def mergeUniqueSortedArrays( A: Array[String], B: Array[String] ): Array[String]= {
val n = A.length
val m = B.length
var C = Array[String]()
var i = 0
var j = 0
while (i < n && j < m) {
if (i == n) {
if ( B(j) != A(i-1) ) {
C :+= B(j)
}
j+=1
}
else if (j == m) {
if ( A(i) != B(j-1) ) {
C :+= A(j)
}
i+=1
}
else {
if ( A(i) < B(j) ) {
if (C.length == 0 || A(i) != C(C.length-1)) {
C :+= A(i)
}
i+=1
}
else if ( B(j) < A(i) ) {
if (C.length == 0 || B(j) != C(C.length-1)) {
C :+= B(j)
}
j+=1
}
else {
if (C.length == 0 || A(i) != C(C.length-1)) {
C :+= A(i)
}
i+=1
j+=1
}
}
}
return C
}
--
NOTE: If the input arrays are not sorted, then you can easily sort the input arrays and it will run in in O( max{(n + m), (n log n)}) time, assuming n>m.
NOTE: O(n + m) time technically assumes that string length is bounded by constant k, but you aren't going to get around that anyway.