DEV Community

loading...

Discussion on: Project Euler Problem 6 Solved with Javascript

Collapse
coolshaurya profile image
Shaurya

In Rust it is pretty simple using ranges and Iterators -

Playground

fn euler_6(n: u32) -> u32 {
    let sum_of_squares: u32 = (1_u32..=n).map(|x| x.pow(2)).sum();
    let square_of_sum: u32 = (1_u32..=n).sum::<u32>().pow(2);

    square_of_sum - sum_of_squares
}
Collapse
codenutt profile image
Jared Author

You say simple, but that looks really complicated to me haha

Thanks for sharing! I'm always interested in what the solutions look like in other languages 👍🏽

Collapse
mburszley profile image
Maximilian Burszley • Edited

I mean, JavaScript has similar constructs:

function euler6(n) {
  const sumOfSquares = range(n + 1).map((x) => x ** 2).reduce((a, b) => a + b);
  const squareOfSum = range(n + 1).reduce((a, b) => a + b).map((x) => x ** 2);

  return squareOfSum - sumOfSquares;
}

function range(n) {
  return [...Array(n).keys()];
}

This could be further simplified with generator functions to get the iterator behavior seen in the Rust example.

Thread Thread
codenutt profile image
Jared Author

Yep, that is definitely one way to do it. I personally prefer more legible code (because I'm a simple human), but this gets the job done.

Thanks for sharing!