Skip to content

Instantly share code, notes, and snippets.

View alexispurslane's full-sized avatar

Alexis Purslane alexispurslane

View GitHub Profile
"Project Euler Problem 1: Multiples of 3 and 5"
((1 to: 999) asArray select: [ :x | (x % 3 = 0) | (x % 5 = 0) ]) sum.
"Project Euler Problem 2: Even Fibonacci numbers"
"SmallInteger>>fib
self = 0
ifTrue: [ ^ 0. ].
self = 1
ifTrue: [ ^ 1. ]
ifFalse: [ ^ (self - 1) fib + (self - 2) fib. ]."
"Project Euler Problem 3: Largest Prime factor"
"
Integer>>isPrime
^ self factors = #(1)
Integer>>factors
^ (1 to: self sqrt) asArray select: [ :i | self % i = 0. ].
"
((600851475143 factors) select: [ :n | n isPrime ]) max
"Project Euler Problem 4: Largest palindrome product"
"
ByteString>>isPalindrome
^ self = self reverse
"
| pals |
pals := { }.
(100 to: 999) asArray do: [ :x |
| ps |
"Project Euler Problem 5: Smallest multiple"
| n |
n := 0.
[ :breakWithValue |
[ true ] whileTrue: [
n := n + 1.
(((1 to: 20) asArray collect: [ :x | n % x = 0 ])
inject: true
into: [ :a :b | a & b ])
ifTrue: [ breakWithValue value: n ]
"Project Euler Problem 6: Sum square difference"
| sumSquares squareSum |
sumSquares := ((1 to: 100) asArray inject: 0 into: [ :sum :x | sum + x squared ]).
squareSum := ((1 to: 100) asArray inject: 0 into: [ :sum :x | sum + x ]) squared.
squareSum - sumSquares.
"For a really mangled one liner, use this:"
((1 to: 100) asArray inject: 0 into: [ :sum :x | sum + x ]) squared - ((1 to: 100) asArray inject: 0 into: [ :sum :x | sum + x squared ])
"Project Euler Problem 7: 10001st prime"
((1 to: 1000001) asArray select: [ :x | x isPrime ]) at: 10001
"Short and to the point!"
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC+4resRjkjsrPwp1SyndyDiMe9maxxVfLl40PVIfcQZ6P8YcjLm9zr0E1Dyd1v0l0kQZb8j2zCb7NC+57yFtUCpZswneMMqs9MOS1yWefZjOM4Z64yy9DjwVPLbelusKVugz79uqPItNl74yzjp3N4S+jE4cYUAF5il3gqelWP70sJmySuRR0SDdAIUc9lBOw4mNn3dJoYWagWFKbaxnKAcXJ9pK9UEA3iQUCyZjyy1nIQaiDDmmAbyR4nLEFdde97Cf9lyvFcTL4VhMEe/VHGZNqvGEt4WfH7OOU0dtVnVRE8ty1Kb3IatJhbPktNqy4xC7zQV5Pru2ouspLTlDjYZgqeZv8oj8ZLmAdSCbsYHZQOn0//UIPf++mnp74MZXYrbt3HIXDdc0SKtGimLTSDCpvvvpPd1kcGyo4pYIQbcOmAhQxWcRtJUBlnxsC9AtO/SATbYNbHGDiiVyksO68H9oxH8R9V0/cgbYbORhdDeE6P+Qhfed7u3UIADGQCEllhI13q8lUGa8KcgMBc8fc4MKAl6jxonI6lrW28+RpYay2BH9b2l+X4dDN7Vc7u4bzVY1Jtx3NXYLyZ4vMlV4zhMoRayy4Z04fYC0pOI4D+bik5F4Cni1MRnWW2VMkQUtOwNU6PWDBi4FUbDRoHEg0MqlSZ0JGyUutD2bZfjQQhEQ== [email protected]
! Project Euler Problem 10: Summation of Primes
1 2000000 [a,b] >array [ prime? ] filter sum
! Project Euler Problem 9: Special Pythagorean triplet
: 3< ( x y z -- ? ) over swap < rot rot < and ;
: pythagorean? ( x y z -- ? ) [ 3< ] [ rot rot dup * rot rot dup * rot + swap dup * = ] 3bi and ;
1 500 [a,b] [| x |
1 500 [a,b] [| y |
1 500 [a,b] [| z |
x y z 3dup pythagorean? [ 3dup + + 1000 = [ 3array ] [ 3drop ] if ] [ 3drop ] if ] each ] each ] each