Wednesday, 23 November 2011

Algo Puzzle #1

I am a jovial fan of algorithmic puzzles so I decided to create some myself and put them on my blog. I will post them one at a time.

You will find the first puzzle down below and the solution will be posted in the comments section over the weekend. The puzzles will gradually get more difficult ;)

Algo Puzzle #1

Write an algorithm that sums a set where each number is from 1 to n in O(1) time. More specifically find an algorithm that computes it with only 3 operations regardless of the set's size.

2 comments:

  1. The solution, written in Java, is:

    int[] data = ...
    int n = data.length;
    int sum = (n*(n+1))/2

    ReplyDelete
  2. Given your answer, I would have worded the problem as: sum the numbers from 1 to n.

    ReplyDelete