user2834729
user2834729

Reputation: 51

Can i return list in Mathematica function?

In my code I'm trying to return list of numbers from my function but it gives me just null.

 sifra[zprava_, klic_] := Module[
  {c, n, e, m, i, z, pocCyklu, slovo},
  pocCyklu = Ceiling[Divide[StringLength[zprava], 5]];
  c = Array[{}, pocCyklu];
  z = Partition[Characters[zprava], 5, 5, 1, {}];
  For[i = 1, i < pocCyklu + 1, i++,
   slovo = StringJoin @ z[[i]];
   m = StringToInteger[slovo];
   n = klic[[1]];
   e = klic[[2]];
   c[[i]] = PowerMod[m, e, n];
  ]
  Return[c]
 ];
 sif = sifra[m, verejny]

After the cycles are done there should be 2 numbers in c.

Print[c] works OK it prints list with 2 elements in it but sif is null.
Return[c] gives me:

Null Return[{28589400926821874625642026431141504822, 2219822858062194181357669868096}]

Upvotes: 4

Views: 5734

Answers (1)

Chris Degnen
Chris Degnen

Reputation: 8655

You could write the function like this:

sifra[zprava_, klic_] := Module[{c, n, e, m, i, z, pocCyklu, slovo},
  pocCyklu = Ceiling[Divide[StringLength[zprava], 5]];
  c = ConstantArray[{}, pocCyklu]; 
  z = Partition[Characters[zprava], 5, 5, 1, {}];
  For[i = 1, i < pocCyklu + 1, i++,
   slovo = StringJoin@z[[i]];
   m = ToExpression[slovo];
   {n, e} = klic;
   c[[i]] = PowerMod[m, e, n]];
  c]

Demonstrating use with example data:

sifra["9385637605763057836503784603456", {124, 2}]

{20, 97, 41, 9, 4, 113, 36}

You could also write the function like this:

sifra[zprava_, {n_, e_}] := Module[{z},
  z = Partition[Characters[zprava], 5, 5, 1, {}]; 
  Map[PowerMod[ToExpression[StringJoin[#]], e, n] &, z]]

Upvotes: 2

Related Questions