Tag Archive for "projecteuler" tag

Problem 3 ver. 1 and 2: brute-force and optimization

March 4th, 2009 by Ivan Lakhturov | 0 Category: Programming | Tags: |

Problem 3

Find the largest prime factor of a composite number.

is a very well known problem called factorization. The fundamental theorem of arithmetics comes in handy.

Brute-force in this case is just iterating from 2 upwards, searching for factors:

  1.         (define (factorize-bruteforce n)
  2.            (define (iterate n x) (if (> x n) (list n) (if (divides? n x) (cons x (iterate (/ n x) x)) (iterate n (+ x 1)))))
  3.            (iterate n 2))

If a factor is found, we divide the number by it, and continue with searching factors of a quotient. We don't need to start from 2 again (see the theorem).

The complexity for finding one factor is O(n) in the worst case. Let us optimize at once, stopping the iteration at sqrt(n). Indeed, a number cannot have a factor greater than its square root. This improves the worst case complexity drastically to O(\sqrt(n)) and this is the classical factorization algo.

  1.         (define (factorize-sqrt-complexity n)
  2.            (define (iterate n x) (if (> x (sqrt n)) (list n) (if (divides? n x) (cons x (iterate (/ n x) x)) (iterate n (+ x 1)))))
  3.            (iterate n 2))

Now, having written additional function (max-list) for finding maximums through lists, we can solve the third problem:

  1.         (define (max-list list) (fold-left max (car list) list))        
  2. (define (solution-3-bruteforce n) (max-list (factorize-bruteforce n)))
  3. (define (solution-3-optimized-1 n) (max-list (factorize-sqrt-complexity n)))

Problem 2 ver. 1: brute-force solution

March 4th, 2009 by Ivan Lakhturov | 0 Category: Programming | Tags: |

I've written the generic procedure to generate lists iteratively:

  1.         (define (generate-list-iteratively seed filter map step stop)
  2.            (define (iterate current) (if (stop current) '()
  3.                                          (let ([rest (iterate (step current))])
  4.                                            (if (filter current) (cons (map current) rest) rest))))
  5.            (iterate seed))

I've refactored (create-filtered-numbers-list from to filter) function into (numbers-filters) and added also (numbers) for future use:

  1.         (define (numbers-filtered from to filter) (generate-list-iteratively from filter (lambda (x) x) (lambda (x) (+ x 1)) (lambda (x) (> x to))))
  2.          (define (numbers from to) (numbers-filtered from to (lambda (x) #t)))

Now the brute-force solution for the problem 2

Find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million

looks like this:

  1.         (define (fibonacci to) (generate-list-iteratively (cons 1 1) (lambda (pair) #t) (lambda (pair) (car pair)) (lambda (pair) (cons (cdr pair) (+ (car pair) (cdr pair)))) (lambda (pair) (> (car pair) to))))
  3. (define (solution-2-bruteforce n) (sum-numbers (filter even? (fibonacci n))))

The complexity is O(n). I decided not to generate a filtered list, but rather first generate, then filter, (fibonacci) function goes to the library for future use (for future functions I will not mention placing into my library). This is an optimal algorithm for generating a Fibonacci sequence, unlike computing the n-th member of it, which can be done more efficiently. However, for computing a sum of members, perhaps, there is a better solution, I will think about it later.

Problem 1 ver. 2: brute-force solution generalized to a list of divisors

March 3rd, 2009 by Ivan Lakhturov | 0 Category: Programming | Tags: |

I refactored the previous solution and extracted such library functions, they could be useful in future:

  1.         (define (some-divides? n divisors) (exists (lambda (x) (divides? n x)) divisors))
  2.          (define (sum-numbers numbers) (fold-left + 0 numbers))
  3.          (define (create-filtered-numbers-list from to filter)
  4.            (define (iterate current) (if (> current to) '()
  5.                                          (let ([rest (iterate (+ current 1))])
  6.                                            (if (filter current) (cons current rest) rest))))
  7.            (iterate from))

I think for these algoritms, where we have to iterate through large lists of numbers, the laziness (e.g. in Haskell) would give slightly more elegant code at certain places.

The first problem solution now becomes:

  1. (define (sum-of-multiples-bruteforce up-to-n divisors)
  2.   (let ([multiples (create-filtered-numbers-list 1 up-to-n (lambda (x) (some-divides? x divisors)))])
  3.     (sum-numbers multiples)))
  5. (define (solution-1-bruteforce n) (sum-of-multiples-bruteforce (- n 1) '(3 5)))

For a list of divisors with length k the number of operations will be k*n. Actually, less than that because of shortcut (exists). Assuming k fixed and small, the complexity is still O(n). We could make use of the not yet written (create-numbers-list) function and filter that afterwards instead of the (create-filtered-numbers-list) function, but let us take less space in memory at once.

Problem 1 ver. 1: brute-force solution

March 2nd, 2009 by Ivan Lakhturov | 0 Category: Programming | Tags: |

Let us start with solutions to Project Euler problems. I will always start with brute-force solutions if those are possible and later on post optimized solutions. Every solution will be given in Scheme (R6RS) along with quick estimate of complexity. The reason for solving those problems is training myself in Scheme and, of course, fun.

Find the sum of all the multiples of 3 or 5 below 1000.


  1. #!r6rs
  2. (import (rnrs))
  4. (define n 1000)
  6. (define (divides? n x) (= (mod n x) 0))
  8. (define (divided-by-3-or-5? n) (or (divides? n 3) (divides? n 5)))
  10. (define (add-dividends n sum) (if (< n 1) sum (add-dividends (- n 1) (if (divided-by-3-or-5? n) (+ sum n) sum))))
  12. (display (add-dividends (- n 1) 0))

This is the simplest straightforward approach. Backward-recursion is used, with tail-recursion optimization, which is obligatory for all Scheme implementations, will be transformed into iteration. Backward direction is to simplify a function signature (otherwise an extra parameter is needed).

The complexity is O(n), assuming the (mod) operation is atomic. More strictly, the number of operations is 2*n. By the way, in R5RS (mod) is called (remainder).

Plans for future

February 16th, 2009 by Ivan Lakhturov | 0 Category: Linux, Programming | Tags: | | | |

Nemerle is waiting, but it have to wait more, while I'm learning Scheme. I have a plan to solve some problems from Project Euler, first with brute-force (however, it is not always possible), then using smarter ways, and post some solutions here under the tags "projecteuler" and "scheme".

Another thing, I am setting up currently a Gentoo Linux system on my workstation, so, some postings about this will come under the tag "gentoo". One of the reasons to install it is an unexpected difficulty with SATA-drives under Windows. The motherboard (Asus M3N78-VM) supports SATA-devices in three modes: SATA (only three accessible), RAID and AHCI. The latest is preferable for me, as I need more than three drives.

It was understandable when WinXP 64-bits (I didn't try any 32-bits systems, as I need more than 4 Gb of RAM) refused to work in AHCI-mode despite all my tricks with this and that, particlularly, manufacturer's drivers embedding with the nLite tool. But when Vista x64 with proper drivers could not load after switching m/b into AHCI, I decided that it's time to try Linux again. I prefer Gentoo, one of the most hardcore distributions available.