# Help with Project Euler #2: undef inits, printing, multiplication by juxtaposition, and more

**URL:** <https://discourse.julialang.org/t/help-with-project-euler-2-undef-inits-printing-multiplication-by-juxtaposition-and-more/106930>\
**Category:** New to Julia\
**Tags:** any\
**Created:** [November 30, 2023, 7:10am UTC](https://discourse.julialang.org/t/help-with-project-euler-2-undef-inits-printing-multiplication-by-juxtaposition-and-more/106930 "2023-11-30T07:10:07Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![chandra](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/chandra/32/207807_2.png) [@chandra](https://discourse.julialang.org/u/chandra)\
**Post date:** [November 30, 2023, 7:10am UTC](https://discourse.julialang.org/t/help-with-project-euler-2-undef-inits-printing-multiplication-by-juxtaposition-and-more/106930/1 "2023-11-30T07:10:07Z")

</div>

```julia
A = [0, 1, undef]
A[3] = 1
println(A)

```

In the above script, is there any way to suppress the `Any` appearing in front of the array values in (square) brackets of array `A`?

---

<div class="post-metadata">

**Author:** ![Benny](https://avatars.discourse-cdn.com/v4/letter/b/49beb7/32.png) [@Benny](https://discourse.julialang.org/u/Benny)\
**Post date:** [November 30, 2023, 7:20am UTC](https://discourse.julialang.org/t/help-with-project-euler-2-undef-inits-printing-multiplication-by-juxtaposition-and-more/106930/2 "2023-11-30T07:20:34Z")

</div>

1. That isn’t how you’d use `undef` to make uninitialized elements. You don’t have an uninitialized element, which would throw an error upon indexing, it’s actually holding an instance that’s used as a flag for uninitialized array construction.

2. Are you sure you want to suppress the array’s element type parameter? It’s important to distinguish that normally. You could instead make a new array with a new element type after all elements are valid `Int`s: `convert(Vector{Int}, A)` or even let it automatically happen in elementwise conversion: `Int.(A)`.

---

<div class="post-metadata">

**Author:** ![chandra](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/chandra/32/207807_2.png) [@chandra](https://discourse.julialang.org/u/chandra)\
**Post date:** [November 30, 2023, 7:36am UTC](https://discourse.julialang.org/t/help-with-project-euler-2-undef-inits-printing-multiplication-by-juxtaposition-and-more/106930/3 "2023-11-30T07:36:38Z")

</div>

That does it. Thanks.

I am doing a Fibonacci sequence problem where `0` and `1` are the first two terms and the remaining ones are generated by the well-known recurrence relation.

I tried `A = [0, 1, 1]` and used `push!` to append the rest. But I had to generate element 3 again within the `while` loop. I used `undef` to avoid that. Perhaps that is not the correct thing to do.

Is there somewhere a script my be posted for dissection and improvement?

It would also help if there were simple but complete use cases like generating the Fibonacci sequence, and doing things with it, in a tutorial. Is there one (or more) such on the Web?

---

<div class="post-metadata">

**Author:** ![Benny](https://avatars.discourse-cdn.com/v4/letter/b/49beb7/32.png) [@Benny](https://discourse.julialang.org/u/Benny)\
**Post date:** [November 30, 2023, 8:04am UTC](https://discourse.julialang.org/t/help-with-project-euler-2-undef-inits-printing-multiplication-by-juxtaposition-and-more/106930/4 "2023-11-30T08:04:31Z")

</div>

Not knowing what your code is, I can’t comment on that exactly. But I can’t imagine the need to make the 3rd uninitialized element in advance.

```julia
julia> A = [0,1]; for _ in 1:10 push!(A, A[end-1] + A[end]) end

julia> println(A) # 2+10=12 terms
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

```

Bear in mind that fixed width integers overflow silently so you’ll have to stop at 47 numbers on 32-bit systems or 93 on 64-bit systems:

```julia
julia> last2 = [0,1]; i = 2; notoverflowed=true; while notoverflowed
           newterm = last2[1] + last2[2]
           if newterm < last2[end]
               notoverflowed = false
           else
               global i += 1
               last2[begin] = last2[end]
               last2[end] = newterm
           end
       end

julia> last2, i
([4660046610375530309, 7540113804746346429], 93)

```

---

<div class="post-metadata">

**Author:** ![kellertuer](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/kellertuer/32/220707_2.png) [@kellertuer](https://discourse.julialang.org/u/kellertuer)\
**Post date:** [November 30, 2023, 8:09am UTC](https://discourse.julialang.org/t/help-with-project-euler-2-undef-inits-printing-multiplication-by-juxtaposition-and-more/106930/5 "2023-11-30T08:09:35Z")

</div>

Besides Bennys solution – here _is_ the place t ask for such improvements 🙂  
Welcome to the Julia discourse 👋

---

<div class="post-metadata">

**Author:** ![chandra](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/chandra/32/207807_2.png) [@chandra](https://discourse.julialang.org/u/chandra)\
**Post date:** [November 30, 2023, 8:18am UTC](https://discourse.julialang.org/t/help-with-project-euler-2-undef-inits-printing-multiplication-by-juxtaposition-and-more/106930/6 "2023-11-30T08:18:32Z")

</div>

My script is shown below for solving the [Euler Two problem](https://projecteuler.net/problem=2):

```julia
# Generate the Fibonacci numbers which do not exceed 4 million
const MAX = 4000000;
F = [0, 1, undef]
i = 3 # Array already has three elements
#
while true
  global i
  F[i] = F[i-1] + F[i-2]
  # println("$(i)" , " ", "$(F[i])") # for troubleshooting
  (F[i] + F[i-1]) <= MAX || break
  push!(F, F[i]) # append to array
  i += 1
end
#
println(i)
println(Int.(F))
#
# Sum of even Fibonacci numbers in F
#
E = F[1:3:end]
println(Int.(E))
println(sum(E)) # This is what we want

```

It looks primitive compared to @Benny’s one-liner! Please dissect it and help me write better scripts. Thanks.

---

<div class="post-metadata">

**Author:** ![DNF](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dnf/32/10191_2.png) [@DNF](https://discourse.julialang.org/u/DNF)\
**Post date:** [November 30, 2023, 8:31am UTC](https://discourse.julialang.org/t/help-with-project-euler-2-undef-inits-printing-multiplication-by-juxtaposition-and-more/106930/7 "2023-11-30T08:31:06Z")

</div>

Make sure to write your code as a function, don’t write it in global scope, and definitely don’t use the `global` keyword. I strongly recommend against it.

Here’s one solution that uses `push!`, if you have an estimate of the array size you will need, you can use that, or let’s say if you know how many numbers you want in advance:

```julia
function myfib(maxval)
    val = i = 1
    F = [0, val]
    while val <= maxval
        push!(F, val)
        val += F[i+=1]
    end
    return F
end

```

---

<div class="post-metadata">

**Author:** ![DNF](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dnf/32/10191_2.png) [@DNF](https://discourse.julialang.org/u/DNF)\
**Post date:** [November 30, 2023, 8:47am UTC](https://discourse.julialang.org/t/help-with-project-euler-2-undef-inits-printing-multiplication-by-juxtaposition-and-more/106930/9 "2023-11-30T08:47:40Z")

</div>

> [@chandra](#):
>
> ```julia
> # Sum of even Fibonacci numbers in F
> #
> E = F[1:3:end]
> println(Int.(E))
> println(sum(E)) # This is what we want
> 
> ```

I didn’t see this at first. Here’s an efficient implementation. It is not super elegant, but it really flies:

```julia
function fibsumeven(maxval)
    prev, current = 0, 1 # previous and updated Fibonacci numbers
    accum = prev # this is the accumulated sum
    prev, current = current, prev + current
    prev, current = current, prev + current
    while current <= maxval
        accum += current # only sum every third Fibo number
        prev, current = current, prev + current
        prev, current = current, prev + current
        prev, current = current, prev + current
    end
    return accum
end

```

Performance comparison with the vector-based implementation:

```julia
julia> @btime sum(@view myfib(4181)[1:3:end])
  279.044 ns (3 allocations: 496 bytes)
3382

julia> @btime fibsumeven(4181)
  6.600 ns (0 allocations: 0 bytes)
3382

```

**Edit:** Here’s one that collapses the repeated lines, if you like that better. It’s also slightly faster:

```julia
function fibsum3(maxval)
    prev, current = 0, 1
    accum = prev
    prev, current = prev + current, prev + 2current
    while current <= maxval
        accum += current
        prev, current = prev + 2current, 2prev + 3current
    end
    return accum
end

```

---

<div class="post-metadata">

**Author:** ![nsajko](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/nsajko/32/221187_2.png) [@nsajko](https://discourse.julialang.org/u/nsajko)\
**Post date:** [November 30, 2023, 11:48am UTC](https://discourse.julialang.org/t/help-with-project-euler-2-undef-inits-printing-multiplication-by-juxtaposition-and-more/106930/10 "2023-11-30T11:48:21Z")

</div>

Slightly nicer way (just as fast though):

```julia
fib_even_next(m2, m1) = 4*m1 + m2

function fib_even_sum(max_val, ini0 = 0, ini1 = 2)
  sum = ini0 
  while ini1 ≤ max_val
    sum += ini1
    n = fib_even_next(ini0, ini1)
    (ini0, ini1) = (ini1, n)
  end
  sum
end

```

The idea is that instead of summing every third Fibonacci number, we could directly operate on the sequence of even Fibonacci numbers.

The Fibonacci numbers are defined by the recurrence a\_n = a\_{n-1} + a\_{n-2}, while even Fibonacci numbers seem to conform to the similar recurrence a\_n = {4 \cdot a\_{n-1}} + a\_{n-2}. The latter was obtained using the [`Guess`](https://fricas.github.io/api/Guess.html) package of [Fricas](https://fricas.github.io), with the `guessPRec` function.

---

<div class="post-metadata">

**Author:** ![DNF](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dnf/32/10191_2.png) [@DNF](https://discourse.julialang.org/u/DNF)\
**Post date:** [November 30, 2023, 1:34pm UTC](https://discourse.julialang.org/t/help-with-project-euler-2-undef-inits-printing-multiplication-by-juxtaposition-and-more/106930/11 "2023-11-30T13:34:42Z")

</div>

> [@nsajko](#):
>
> The idea is that instead of summing every third Fibonacci number, we could directly operate on the sequence of even Fibonacci numbers.

That’s also what is going on in `fibsum3`, only using a slightly different recurrence.

---

<div class="post-metadata">

**Author:** ![chandra](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/chandra/32/207807_2.png) [@chandra](https://discourse.julialang.org/u/chandra)\
**Post date:** [November 30, 2023, 2:34pm UTC](https://discourse.julialang.org/t/help-with-project-euler-2-undef-inits-printing-multiplication-by-juxtaposition-and-more/106930/12 "2023-11-30T14:34:27Z")

</div>

Thanks for this.

I found the line `val += F[i+=1]` a little difficult to get my head around. I wanted something a little easier that I could relate directly to the recurrence relation. So, I tried the following:

```julia
function myfib(maxval)
    val = 1
    F = [0, val]
    while val <= maxval
        push!(F, val)
        val += F[end-1]
    end
    return F
end

```

In the process, the pesky `i` which I had to previously declare global has also vanished. I think the moral is that wrapping the whole thing within a function does away with `local` versus `global` variables.

I am grateful for your example. The other examples here have a “horsepower” that is a little too high for me to grasp straightaway! More exposure to the Julia style will hopefully demystify them.

---

<div class="post-metadata">

**Author:** ![chandra](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/chandra/32/207807_2.png) [@chandra](https://discourse.julialang.org/u/chandra)\
**Post date:** [November 30, 2023, 2:52pm UTC](https://discourse.julialang.org/t/help-with-project-euler-2-undef-inits-printing-multiplication-by-juxtaposition-and-more/106930/13 "2023-11-30T14:52:28Z")

</div>

What do the expressions `2current` and `3current` mean? I searched the docs but could not find the _name_ for this action.

Are they a short-form for multiplication? If so, how is ambiguity in meaning avoided?

---

<div class="post-metadata">

**Author:** ![nsajko](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/nsajko/32/221187_2.png) [@nsajko](https://discourse.julialang.org/u/nsajko)\
**Post date:** [November 30, 2023, 5:18pm UTC](https://discourse.julialang.org/t/help-with-project-euler-2-undef-inits-printing-multiplication-by-juxtaposition-and-more/106930/14 "2023-11-30T17:18:40Z")

</div>

Yeah, it’s implicit multiplication by a constant: [Numeric Literal Coefficients](https://docs.julialang.org/en/v1/manual/integers-and-floating-point-numbers/#man-numeric-literal-coefficients)

---

<div class="post-metadata">

**Author:** ![bertschi](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/bertschi/32/33462_2.png) [@bertschi](https://discourse.julialang.org/u/bertschi)\
**Post date:** [November 30, 2023, 5:48pm UTC](https://discourse.julialang.org/t/help-with-project-euler-2-undef-inits-printing-multiplication-by-juxtaposition-and-more/106930/15 "2023-11-30T17:48:31Z")

</div>

Here is a functional solution:

```julia
using Chain, IterTools

fibo_step(a, b) = (b, a+b)

@chain (0, 1) begin
    IterTools.iterated(splat(fibo_step), _)
    Iterators.map(first, _)
    Iterators.takewhile(<(4000000), _)
    collect(_)
end

```

---

<div class="post-metadata">

**Author:** ![DNF](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dnf/32/10191_2.png) [@DNF](https://discourse.julialang.org/u/DNF)\
**Post date:** [November 30, 2023, 6:15pm UTC](https://discourse.julialang.org/t/help-with-project-euler-2-undef-inits-printing-multiplication-by-juxtaposition-and-more/106930/16 "2023-11-30T18:15:13Z")

</div>

One central point is that if you are just looking to calculate an aggregate scalar value (eg. the sum of the even numbers), it is wasteful to first build a full vector, and then later iterate and sum over it. If you can “sum as you go”, you can often get a _huge_ performance payoff. So as a general rule, I always ask myself if I _really_ need to build an array.

---

<div class="post-metadata">

**Author:** ![chandra](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/chandra/32/207807_2.png) [@chandra](https://discourse.julialang.org/u/chandra)\
**Post date:** [December 1, 2023, 5:38am UTC](https://discourse.julialang.org/t/help-with-project-euler-2-undef-inits-printing-multiplication-by-juxtaposition-and-more/106930/17 "2023-12-01T05:38:09Z")

</div>

I think this is an explanation for `fibsun3` and it is so much clearer now.

I also appreciate the general philosophy of why it is wasteful to use arrays in such cases.

Thank you.

---

<div class="post-metadata">

**Author:** ![chandra](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/chandra/32/207807_2.png) [@chandra](https://discourse.julialang.org/u/chandra)\
**Post date:** [December 1, 2023, 5:39am UTC](https://discourse.julialang.org/t/help-with-project-euler-2-undef-inits-printing-multiplication-by-juxtaposition-and-more/106930/18 "2023-12-01T05:39:15Z")

</div>

Thank you for the links to Fricas and Guess.

---

<div class="post-metadata">

**Author:** ![chandra](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/chandra/32/207807_2.png) [@chandra](https://discourse.julialang.org/u/chandra)\
**Post date:** [December 1, 2023, 5:41am UTC](https://discourse.julialang.org/t/help-with-project-euler-2-undef-inits-printing-multiplication-by-juxtaposition-and-more/106930/19 "2023-12-01T05:41:52Z")

</div>

In light of the wealth of help I have got here, may I suggest something.

**Could someone with administrator privileges please change the subject of this thread to better reflect the knowledge contained herein.**

Thank you all.

---

<div class="post-metadata">

**Author:** ![Benny](https://avatars.discourse-cdn.com/v4/letter/b/49beb7/32.png) [@Benny](https://discourse.julialang.org/u/Benny)\
**Post date:** [December 1, 2023, 9:42am UTC](https://discourse.julialang.org/t/help-with-project-euler-2-undef-inits-printing-multiplication-by-juxtaposition-and-more/106930/20 "2023-12-01T09:42:26Z")

</div>

The title of your thread should have a pencil icon at the end, click it and you can edit the title. Your comments will also have a pencil icon at the bottom right with this functionality. Press the appearing check icon to save changes and the X icon to discard changes.

---

<div class="post-metadata">

**Author:** ![Nathan\_Boyer](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/nathan_boyer/32/14825_2.png) [@Nathan\_Boyer](https://discourse.julialang.org/u/Nathan_Boyer)\
**Post date:** [December 1, 2023, 3:27pm UTC](https://discourse.julialang.org/t/help-with-project-euler-2-undef-inits-printing-multiplication-by-juxtaposition-and-more/106930/21 "2023-12-01T15:27:08Z")

</div>

> [@chandra](#):
>
> ```julia
> function myfib(maxval)
> val = 1
> F = [0, val]
> while val <= maxval
> push!(F, val)
> val += F[end-1]
> end
> return F
> end
> 
> ```

That is pretty much how I would write it. Except you should start with just a 1-element vector or else the original prompt in the link of starting with [1,2] does not work, i.e. `F = [0, val]` should just be `F[0]`. Then `val` will be pushed to `F` inside the loop.

```julia
function myfib(maxval=4e6, first=0, second=1)
    val = second
    F = [first]
    while val <= maxval
        push!(F, val)
        val += F[end-1]
    end
    return F
end

```

Even the literal version without `val` isn’t much slower.

```julia
function myfib_nathan(maxval=4e6, first=0, second=1)
    F = [first, second]
    while F[end] < maxval
        push!(F, F[end] + F[end-1])
    end
    return F[1:end-1]
end

```

```julia-repl
julia> @btime myfib_DNF(4e6)
  244.149 ns (3 allocations: 496 bytes)

julia> @btime myfib_nathan(4e6)
  302.834 ns (4 allocations: 832 bytes)

```

[Next page](https://discourse.julialang.org/t/help-with-project-euler-2-undef-inits-printing-multiplication-by-juxtaposition-and-more/106930.md?page=2)
