# Converting sequece of code into a function [closed]

I constructed a pretty basic sieve of Eratosthenes and would like to use it as a function rather than copy pasting output, how do I achieve

n = 5000000;
start = UnixTime[];
bsclst = Complement[Union[Range[3, n, 2], {2}], Range[9, n, 3]];
For[i = 3, i < Length[bsclst], i++,
If[bsclst[[i]] > Sqrt[n], Break[]];
bsclst =
Complement[bsclst, Array[#*bsclst[[i]] &, IntegerPart[n/bsclst[[i]]] - 1, 2]]]
Total[bsclst]
stop = UnixTime[];
Print["Finding Primes up to ", n, " took ", stop - start, " Seconds"]

838596693108

Finding Primes up to 5000000 took 7 Seconds


All this does is take a number $n$ and return list/sum of primes up to $n$

Is there a general way to convert a sequence of top-level computations to function or would each case be done differently?

• What have you tried so far? Did you search the documentation? Did you google? Please read the first two sections: reference.wolfram.com/language/tutorial/… Sep 21, 2017 at 13:11
• @Szabolcs Second Section helped, thank you. Couldnt find this in offline documentation as my wordings were a bit ...Ambiguous Sep 21, 2017 at 13:37

func[n_] := Module[{},
start = UnixTime[];
bsclst = Complement[Union[Range[3, n, 2], {2}], Range[9, n, 3]];
For[i = 3, i < Length[bsclst], i++,
If[bsclst[[i]] > Sqrt[n], Break[]];
bsclst =
Complement[bsclst,
Array[#*bsclst[[i]] &, IntegerPart[n/bsclst[[i]]] - 1, 2]]]
Total[bsclst]
stop = UnixTime[];
Print["Finding Primes up to ", n, " took ", stop - start,
" Seconds"]]


Output:

func[5000000]


Finding Primes up to 5000000 took 4 Seconds

You can get the output as vector like this:

func[n_] := Module[{},
start = UnixTime[];
bsclst = Complement[Union[Range[3, n, 2], {2}], Range[9, n, 3]];
For[i = 3, i < Length[bsclst], i++,
If[bsclst[[i]] > Sqrt[n], Break[]];
bsclst =
Complement[bsclst,
Array[#*bsclst[[i]] &, IntegerPart[n/bsclst[[i]]] - 1, 2]]];
stop = UnixTime[];
{Total[bsclst],stop - start}
]


output:

func[5000000]


{838596693108, 4}

But maybe you want the timing not just rounded to seconds then use Timing[], around the function, or allready as part of the definition like

func[n_] := Module[{},
Timing[
bsclst = Complement[Union[Range[3, n, 2], {2}], Range[9, n, 3]];
For[i = 3, i < Length[bsclst], i++,
If[bsclst[[i]] > Sqrt[n], Break[]];
bsclst =
Complement[bsclst,
Array[#*bsclst[[i]] &, IntegerPart[n/bsclst[[i]]] - 1, 2]]];
stop = UnixTime[];
Total[bsclst]
]
]


with

func[500000]


Output:

{0.149548, 9914236195}

• It doesnt output Total[bsclst]? Moreover, can i return the list (bsclst). Sorry im not very familiar with Mathematica, only done python so far Sep 21, 2017 at 13:34
• Nvm, found it, just use Return[] instead of Print[]. Whats the difference between using Module[] and using just parentheses around the block? Sep 21, 2017 at 13:41
• @AnvitGarg parentheses is totally fine. Module allows you to scope variables if you want that. Sep 21, 2017 at 19:19