Greetings, fellow neophyte! 😃
I have a tiny little bit of experience in C, but a friend of mine recently had me read The Little Schemer, which has captured my soul. So, I'll be using Racket, instead. Racket is one hell of a language. It's got the flexibility and grace that the Lisps are famous for, to be sure, but it's also got a jungle of almost-identical constructs—I'm looking at you, for family! 😵 That said, it's been a really fun language to play around with, and once I'm a little more confident in my abilities I'm going to tear into the other libraries like a rack of baby-back ribs!
To demonstrate just how flexible Racket is, here's a handful of different ways to solve Problem 1.
#lang racket
(require math/number-theory)
;; Problem 1: Multiples of 3 and 5
;; Find the sum of all the multiples of 3 or 5 below 1000.
; Solution 0: Checks whether num is divisible by 3 or 5
(define (good-num? num)
(or (divides? 3 num)
(divides? 5 num)))
; Solution 1: Simple recursion. Needs to be called (sum-of-divisors1 (sub1 max)), else it'll include the max number in addition to the ones below it. 😥
(define (sum-of-divisors1 num)
(cond
[(zero? num) 0]
[(good-num? num) (+ num (sum-of-divisors1 (sub1 num)))]
[else (sum-of-divisors1 (sub1 num))]))
; Solution 2: Tail recursion. They say it runs way faster this way! 🎾💨
(define (sum-of-divisors2 max)
(define (sod sum num)
(cond
[(zero? num) sum]
[(good-num? num) (sod (+ sum num) (sub1 num))]
[else (sod sum (sub1 num))]))
(sod 0 (sub1 max)))
; Solution 3: Higher-order functions. This is probably the most ✨elegant✨ solution of the bunch!
(define (sum-of-divisors3 max)
(foldl + 0 (filter good-num? (range max))))
; Solution 4: For loop. There's a bunch of different versions of the for loop in Racket, and a bunch of them could've worked here, but I chose the simplest.
(define (sum-of-divisors-for max)
(for/sum ([number (range max)])
(if (good-num? number)
number
0)))
(Please don't copy my solutions! If you do, then you won't learn anything! Plus, I'll get really mad, and I'll keep being mad at you until you make up a new one! 😤)