Project Euler on a Microcontroller
shawnnapora.github.io
shawnnapora.github.io
https://gist.github.com/vmunoz82/49de4c63bee1768283162ec5406...
class Euler(Elaboratable):
def __init__(self):
self.output = Signal(19)
def elaborate(self, platform):
m = Module()
count5 = Signal(3)
c3, c5 = Signal(17), Signal(18)
cond3, cond5 = (c3 < 1000) & (count5 != 0), (c5 < 1000) & (count5 < 3)
m.d.sync += count5.eq(Mux(count5 == 4, 0, count5+1))
m.d.sync += [
c3.eq(c3+3),
c5.eq(Mux(cond5, c5+5, c5))
]
m.d.sync += self.output.eq(self.output +
Mux(cond3, c3, 0)+Mux(cond5, c5, 0))
return mSo as the simulation code shows, it just tick the clock (with the "yield" statement) and read the "output" register and print it.
Of course you could connect this "Project Euler 1 accelerator" to a CPU, a SoC or whatever, or just connect LEDs directly to "output"
n 3-count 5-count
1 1 1
2 2 2
3 3 3
4 1 4
...
So the check is just a cpi (compare immediate) instruction for whether the particular counter is 3 or 5. Which is probably faster than bit twiddling, especially since they don't have a pop count instruction available in the instruction set. On an instruction set with that, I imagine it would be a useful trick though.>> On an instruction set with that [pop count], I imagine it would be a useful trick though.
Some of my early post-grad work was done in MATLAB and I remember having to find ways to collapse loops into matrix operations so that MATLAB could finish executing the programs in a reasonable amount of time.
I actually think somewhere in the MATLAB documentation it explains that all loop constructs in MATLAB are compiled into matrix operations by the interpreter before MATLAB executed anything.
Which is why MATLAB is so often orders of magnitude slower than Python even though they're supposed to be able to solve similar problems. The idiomatic MATLAB way of writing programs just requires a very matrix-y view of the world.
The positive part about virtual machines in general would be the ease of debugging and sharing/validating answers, though.
Used transistor count as the blog suggests is clearly the best metric