Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7646853
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T10:18:56+00:00 2026-05-31T10:18:56+00:00

I wrote this code to find the prime numbers less than the given number

  • 0

I wrote this code to find the prime numbers less than the given number i in scala.

def findPrime(i : Int) : List[Int] = i match {
    case 2 => List(2)
    case _ => {
    val primeList = findPrime(i-1)
    if(isPrime(i, primeList)) i :: primeList else primeList
    }
}

def isPrime(num : Int, prePrimes : List[Int]) : Boolean = prePrimes.forall(num % _ != 0)    

But, I got a feeling the findPrime function, especially this part:

case _ => {
    val primeList = findPrime(i-1)
    if(isPrime(i, primeList)) i :: primeList else primeList
}

is not quite in the functional style.

I am still learning functional programming. Can anyone please help me improve this code to make it more functional.

Many thanks.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T10:18:58+00:00Added an answer on May 31, 2026 at 10:18 am

    The style looks fine to me. Although the Sieve of Eratosthenes is a very efficient way to find prime numbers, your approach works well too, since you are only testing for division against known primes. You need to watch out however–your recursive function is not tail recursive. A tail recursive function does not modify the result of the recursive call–in your example you prepend to the result of the recursive call. This means that you will have a long call stack and so findPrime will not work for large i. Here is a tail-recursive solution.

    def primesUnder(n: Int): List[Int] = {
      require(n >= 2)
    
      def rec(i: Int, primes: List[Int]): List[Int] = {
        if (i >= n) primes
        else if (prime(i, primes)) rec(i + 1, i :: primes)
        else rec(i + 1, primes)
      }
    
      rec(2, List()).reverse
    }
    
    def prime(num: Int, factors: List[Int]): Boolean = factors.forall(num % _ != 0)
    

    This solution isn’t prettier–it’s more of a detail to get your solution to work for large arguments. Since the list is built up backwards to take advantage of fast prepends, the list needs to be reversed. As an alternative, you could use an Array, Vector or a ListBuffer to append the results. With the Array, however, you would need to estimate how much memory to allocate for it. Fortunately we know that pi(n) is about equal to n / ln(n) so you can choose a reasonable size. Array and ListBuffer are also a mutable data types, which goes again your desire for functional style.

    Update: to get good performance out of the Sieve of Eratosthenes I think you’ll need to store data in a native array, which also goes against your desire for style in functional programming. There might be a creative functional implementation though!

    Update: oops! Missed it! This approach works well too if you only divide by primes less than the square root of the number you are testing! I missed this, and unfortunately it’s not easy to adjust my solution to do this because I’m storing the primes backwards.

    Update: here’s a very non-functional solution that at least only checks up to the square root.

    rnative, you could use an Array, Vector or a ListBuffer to append the results. With the Array, however, you would need to estimate how much memory to allocate for it. Fortunately we know that pi(n) is about equal to n / ln(n) so you can choose a reasonable size. Array and ListBuffer are also a mutable data types, which goes again your desire for functional style.

    Update: to get good performance out of the Sieve of Eratosthenes I think you’ll need to store data in a native array, which also goes against your desire for style in functional programming. There might be a creative functional implementation though!

    Update: oops! Missed it! This approach works well too if you only divide by primes less than the square root of the number you are testing! I missed this, and unfortunately it’s not easy to adjust my solution to do this because I’m storing the primes backwards.

    Update: here’s a very non-functional solution that at least only checks up to the square root.

    import scala.collection.mutable.ListBuffer
    
    def primesUnder(n: Int): List[Int] = {
      require(n >= 2)
    
      val primes = ListBuffer(2)
      for (i <- 3 to n) {
        if (prime(i, primes.iterator)) {
          primes += i
        }
      }
    
      primes.toList
    }
    
    // factors must be in sorted order
    def prime(num: Int, factors: Iterator[Int]): Boolean = 
      factors.takeWhile(_ <= math.sqrt(num).toInt) forall(num % _ != 0)
    

    Or I could use Vectors with my original approach. Vectors are probably not the best solution because they don’t have the fasted O(1) even though it’s amortized O(1).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I wrote this code to create a list from en number of arguments given
I wrote this code to find all possible permutations of some numbers. But i
I wrote this simple code in python to calculate a given number of primes.
I wrote this tiny code: #include <stdio.h> int main() { size_t temp; temp =
I wrote this little code std::map<int,template<class T>> map_; map_.insert(make_pair<int,message>(myMsg.id,myMsg)); but the compiler doesn't seem
I wrote this piece of code to scan a directory for files newer than
This c++ code prints out the following prime numbers: 3 5 7 11 13
I try to realize shopping cart, and i wrote this code: if cookies[:shopping_cart] Cart.find(cookies[:shopping_cart][:value])
I wrote this code in C# to encrypt a string with a key: private
I wrote this code. The constructor works normally, but in the destructor I get

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.