-1

I have a problem how to find best, worst, average case in armstrong number algorithm?

Here the pseudo-code :

Declaration:
      n : integer
      Sum : integer
      Temp : integer
      Rem  : integer
Algorithm:
      Input(n)
      Temp <-- n
      Sum <-- 0
      Rem <--- 0
      While ( n != 0 ) do
               Rem <-- n mod 10
               Sum <-- Sum + Rem * Rem * Rem
               n <-- n / 10
      Endwhile

      if ( Sum = n ) then
         output (n ," is Armstrong number")
     else
         Output(n," is not armstrong number")
         Endif

I find

Best-case : Tmin(n) = 3,

Worst-case : Tmax(n) = 3n,

Average-case : Tavg(n) = 3 [ n(n+1)/2 ] / n = 3(n+1)/2 = 3n+3/2

Sn= n(n+1)/2 The sum of the natural numbers from 1 to n

Thanks for you help.

Nezza
  • 3
  • 2
  • would Tmax(n) not be log(n)? why do you think Tmin and Tavg wd be different? – e_noether Nov 04 '15 at 05:01
  • @emmy because the step to find/calculate worst-case and average-case is different, I think – Nezza Nov 04 '15 at 05:09
  • possible duplicate: http://cs.stackexchange.com/q/23593/755. I suggest you read through the methods described there, try applying them to your problem, work through what you get when applying those methods to your problem, and edit the question to show your work. – D.W. Nov 04 '15 at 06:04
  • 1
    What @D.W. said, plus we don't appreciate "check my answer" posts -- in particular if you do not give the intermediate steps to verify! – Raphael Nov 04 '15 at 10:48

1 Answers1

0

Essentially, the only thing that affects the run time of your algorithm is the loop. This will iterate for as many times as it takes to get from $n$ to 0 by dividing $n$ by 10. So we're asking, how many times will it be before $n, n/10, n/100, n/1000, \dotsc$ gets to 0? That is, when is $n/10^k = 0$? Clearly, when $k=\log_{10}n$. The loop is unaffected by any difference between the $n$ values, as long as they have the same number of decimal digits, so best-case time = worst-case time = average-case time = $3\log n$ plus some constant overhead for setting the variables and displaying the output.

Rick Decker
  • 14,826
  • 5
  • 42
  • 54