1
\$\begingroup\$

I usually write Euler solutions in Javascript. On problems requiring very large integers I have decided to learn Scala and take advantage of BigInt. I wrote a solution to Euler025, it works fast but reads like Javascript. Will the reviewer please comment on how to write this solution more idiomatically and, if you have a JS background, what resources did you find useful to learn syntax/best practices?

What is the index of the first term in the Fibonacci sequence to contain 1000 digits?

Solution:

def e25(): Int = {
  var a = BigInt("1")
  var b = BigInt("1")
  var index = 3

  while(index > 0) {
    val temp = a + b
    if (temp.toString().length() > 999) {
      return index
    }
    index += 1
    a = b
    b = temp
  }
  index
}

println(e25())
\$\endgroup\$
1
\$\begingroup\$

You solved the problem in one shot, going against Functional Programming principles that Scala encourages:

What is the index of the first term in the Fibonacci sequence to contain 1000 digits?

Can be decomposed in:

  • Index of the first term that satisfies a predicate. (Built-in).
  • Digits of a number.
  • Length of a sequence (Built-in).
  • Lazy (for efficiency) Fibonacci generator.
  • Main, putting those functions together.
\$\endgroup\$
  • \$\begingroup\$ Will go for a re-write that at least drops the vars and while-loop as it looks like those are big warning signs of imperative programming. Do you have specific advice or readings about moving towards functional programming? Thanks You. \$\endgroup\$ – boatSoap Oct 6 '15 at 17:55
  • \$\begingroup\$ @boatSoap a partial re-write will not give real benefit. Functional programming is so different from imperative programming... Functional programming encourages tiny pure functions, that may be used together to achieve your goal. Which languages are you familiar with? Many mainstream languages contain functional features. \$\endgroup\$ – Caridorc Oct 6 '15 at 19:31
  • \$\begingroup\$ I do mean a full re-write ina function style. I managed to solve E48 functionally. I come from Javascript. I originally started Project Euler to get a grasp on high-order functions of the Array and Object Prototypes .map(), .filter(), .reduce() and so on. \$\endgroup\$ – boatSoap Oct 6 '15 at 19:50
  • \$\begingroup\$ @boatSoap we should discuss this in chat -> chat.stackexchange.com/rooms/29947/starting-out-with-fp as off-topic comments on the main site should be avoided. Or not, only if you are interested \$\endgroup\$ – Caridorc Oct 6 '15 at 19:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.