Project Euler #1 - Sum of Multiples of 3 or 5


C Solution Walkthrough

  1. Problem Statement



  2. My C Solution

  3. #include <stdint.h>
    #include <stdio.h>
    
    #ifndef N
    #define N (1000ul)
    #endif // N
    
    uint64_t solve(uint64_t n)
    {
        uint64_t sum = 0;
        for (uint64_t i = 3; i < n; i++)
        {
            if (i % 3 == 0 || i % 5 == 0)
            {
                sum += i;
            }
        }
        return sum;
    }
    
    int main()
    {
        fprintf(
                stdout,
                "The sum of all the multiples of 3 or 5 below %lu is: %lu\n",
                N,
                solve( N ));
        return 0;
    }
    


  4. High-Level Approach



  5. Header Files and Types

  6. #include <stdint.h>
    #include <stdio.h>
    



  7. The N macro (configurable limit)

  8. #ifndef N
    #define N (1000ul)
    #endif // N
    

    gcc -DN=5000 euler1.c -o euler1
    ./euler1
    



  9. The solve Function

  10. uint64_t solve(uint64_t n)
    {
        uint64_t sum = 0;
        for (uint64_t i = 3; i < n; i++)
        {
            if (i % 3 == 0 || i % 5 == 0)
            {
                sum += i;
            }
        }
        return sum;
    }
    



  11. The main Function

  12. int main()
    {
        fprintf(
                stdout,
                "The sum of all the multiples of 3 or 5 below %lu is: %lu\n",
                N,
                solve( N ));
        return 0;
    }
    



  13. Complexity and Performance




Haskell Solution Walkthrough

  1. Problem Statement



  2. The Full Haskell Solution
  3. main :: IO ()
    main = print $ sum [x | x <- [1 .. 999], x `mod` 3 == 0 || x `mod` 5 == 0]
    



  4. The Type Signature
  5. main :: IO ()
    



  6. The Body of main
  7. main = print $ sum [x | x <- [1 .. 999], x `mod` 3 == 0 || x `mod` 5 == 0]
    



  8. List Comprehension
  9. [x | x <- [1 .. 999], x `mod` 3 == 0 || x `mod` 5 == 0]
    



  10. Using sum
  11. sum [x | x <- [1 .. 999], x `mod` 3 == 0 || x `mod` 5 == 0]
    



  12. Printing the Result
  13. print $ sum [...]
    



  14. Putting It All Together

  15. -- Step 1: Generate the list
    [x | x <- [1..999], x `mod` 3 == 0 || x `mod` 5 == 0]
    -- => [3,5,6,9,10,12,15,18,20,...,999]
    
    -- Step 2: Sum the list
    sum [3,5,6,9,10,12,15,...,999]
    -- => 233168
    
    -- Step 3: Print the result
    print 233168
    



  16. Performance Consideration



  17. Alternative: Using Higher-Order Functions
  18. main :: IO ()
    main = print . sum . filter f $ [1..999]
      where f x = x `mod` 3 == 0 || x `mod` 5 == 0