Home > Power Sums > Power sum in Ruby

Power sum in Ruby

The logo, selected as winner of the Ruby Logo ...

The logo, selected as winner of the Ruby Logo Contest (Photo credit: Wikipedia)

1^m + 2^m + \ldots + n^m = ?

It is not easy to calculate if n is 50, nad m is 9. Here Ruby comes for help. If you had already installed Ruby 1.8 or Ruby 1.9, open terminal (in Linux) type irb and press enter. Then type following (don’t type > sign) :

>sum(n,m)
>return 1 if n == 1
>sum(n-1,m) + n^m if n > 1
>end

It is all, now type sum(50,9) and you will get the answer…

 

 

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: