Mathematica

by

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.

Tags: , ,

2 Responses to “Mathematica”

  1. Talegari Says:

    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

  2. Eastsun Says:

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

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

Google photo

You are commenting using your Google 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 )

Connecting to %s


%d bloggers like this: