I tried the problem first in Mathematica, and then in Sage. Here is my Mathematica code:

j = 0;

For[i = 1, i < 1000, i++,
j += If[Divisible[i, 3], i, If[Divisible[i, 5], i, 0]]];
j
[/sourcecode]
Mathematica claims a running time of 0.005759 seconds. Now here is the code I ran in Sage:
[sourcecode language='python']
j=0;
def is_divisible_by(number,divisor):
return number%divisor == 0
for i in range(1,1000):
if is_divisible_by(i,3):
j+=i
if is_divisible_by(i,3)==false:
if is_divisible_by(i,5):
j+=i
print(j)
[/sourcecode]
Sage tells me that it took 0.02s to run that code. Then I saw some of your previouly posted solutions, and amended my code so that the for loop looked like
[sourcecode language='python']
for i in range(1,1000):
if is_divisible_by(i,3) or is_divisible_by(i,5):
j+=i
[/sourcecode]
(i.e., I made my code almost exactly the same as some of the previously posted solutions). Now Sage says it takes 0.01s to compute the answer.

### Like this:

Like Loading...

*Related*

Tags: cmd, mathematica, prob1

This entry was posted on May 14, 2009 at 9:25 am and is filed under Uncategorized. You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.

May 15, 2010 at 8:31 am |

I think this can be improved on Mathematica and possibly still better ways of writing the same code on Mathematica could exist.

f[] := Module[{j = 0},

Do[If[Divisible[i, 3] || Divisible[i, 5], j = j + i], {i, 1000}];

Return[j];

];

In[6]:= f[] // Timing

Out[6]= {0.015, 234168}

Time Taken:.015s

November 26, 2010 at 7:23 am |

Sum[If[Divisible[n, 3] || Divisible[n, 5], n, 0], {n, 1000}]