Jump to content

Homework help - Algorithm complexity

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
3 replies to this topic

#1
Pillager

Pillager

    Newbie

  • Members
  • Pip
  • 1 posts
Hi guys, I was wondering if anyone could give me any tips on these exercises I am trying.

I'm trying to make an algorithm that runs proportional to O(log(n²)).

The attempt I've coded (in java) looks something like this:

int count = 0;


for(int i=1; i<n; i*=2) {


  for(int j=0; j<n; j++) {


    for(int k=0; k<n; k++) {


     count++; }}}



Now from my understanding I thought that the two inner loops would give an N² complexity, which would then be multiplied by the outer loop which has a log complexity. I assume something fairly fundamental is tripping me up, I suspect either the order of my loops or a math error based on the log part.

Anyway thanks for any advice you can give, feel free to give any general tips on algorithm analysis if you want as I think I only have a vague grasp on the topic.

#2
morefood2001

morefood2001

    Speaks fluent binary

  • Members
  • PipPipPipPipPipPipPipPip
  • 1,720 posts
This algorithm is an N^3 algorithm.

To get logarithm time, you need recursion so that you only hit a fraction of the total number of values. Tree data structures are good at getting logarithmic time.

For example, if you have 5 elements, you will only touch through 4 of them.

#3
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
O(log(n^2)) is actually O(2*log(n)) or O(log(n)). A typical algorithm of this complexity is a binary search.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#4
John

John

    Writes binary right handed and hex left handed

  • Moderators
  • 6,321 posts
The "number guessing game" is generally a good example of an O(log(n)) algorithm.