Project Euler is a series of mathematical and programming problems.
These problems have been modified to have, at most, 16-bit answers.
1 Multiples of 3 or 5
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 530(#0212). Answer: 65103(#fe4f)
( res ) LIT2r 0000 #0212 #0000 &loop ( multiple of 3 ) DUP2 #0003 MOD2 #0000 NEQ2 ,&fail-3 JCN STH2k ADD2r ,&resume JMP &fail-3 ( multiple of 5 ) DUP2 #0005 MOD2 #0000 NEQ2 ,&fail-5 JCN STH2k ADD2r ,&resume JMP &fail-5 &resume INC2 GTH2k ,&loop JCN POP2 POP2 ( res ) STH2r
2 Even Fibonacci numbers
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89. By considering the terms in the Fibonacci sequence whose values do not exceed 32'000(#7d00), find the sum of the even numbers. Answer: 60696(#ed18)
( res ) LIT2r 0000 #0000 #0001 &loop ADD2k ROT2 POP2 ( even number ) DUP2 #0001 AND2 NIP ,&skip JCN STH2k ADD2r &skip DUP2 #7d00 LTH2 ,&loop JCN POP2 POP2 ( res ) STH2r
3 Largest prime factor
The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 64'485(#fbe5)? Answer: 1433(#0599)
#0002 #fbe5 STH2k &loop STH2kr OVR2 MOD2 #0000 NEQ2 ,&no-factor JCN DUP2 ,is-prime JSR #01 NEQ ,&no-factor JCN ,&end JMP &no-factor #0001 SUB2 LTH2k ,&loop JCN &end NIP2 POP2r
To find if a number is prime:
@is-prime ( value* -- bool ) DUP2 #0002 EQU2 ,&pass-end JCN DUP #01 AND #00 EQU ,&fail-end JCN #0003 &loop OVR2 OVR2 DUP2 MUL2 LTH2 ,&pass JCN OVR2 OVR2 DIV2k MUL2 EQU2 ,&fail JCN INC2 INC2 ,&loop JMP &fail POP2 &fail-end POP2 #00 JMP2r &pass POP2 &pass-end POP2 #01 JMP2r
4 Largest palindrome product
A palindromic number reads the same both ways. The largest hexadecimal palindrome made from the product of two 2-digit below #40 is #0990 = #30 × #33. Find the largest palindrome made from the product of two digit below #c0. Answer: #b8 × #bb(#8668)
( res ) LIT2r 0000 #c001 &a #c001 &b ( iterators ) OVR2 NIP OVR SWP ( product ) #00 SWP ROT #00 SWP MUL2 DUP2 ,is-palindrome JSR #00 EQU ,&skip JCN STH2k GTH2kr STHr JMP SWP2r POP2r &skip POP2 INC GTHk ,&b JCN POP2 INC GTHk ,&a JCN POP2 STH2r
To find if a number is a palindrome:
@is-palindrome ( value* -- bool ) DUP2 #f00f AND2 #40 SFT EQU STH #0ff0 AND2 #04 SFT EQU STHr AND JMP2r
5 Smallest multiple
6 Sum square difference
7 10001st prime
8 Largest product in a series
9 Special Pythagorean triplet
10 Summation of primes
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below 912(#0390). Answer: 64616(#fc68)
( res ) LIT2r 0000 #03a0 #0000 &loop DUP2 ,is-prime JSR #00 EQU ,&skip JCN STH2k ADD2r &skip INC2 GTH2k ,&loop JCN &end POP2 POP2 ( res ) STH2r