Question

let n be an integer and A = {2,3,...,10} and I want to do as follows:

  1. divide n to 2, so there is a reminder r2 and a quotient q2.
  2. divide q2 to 3, so there is a reminder r3 and a quotient q3.
  3. we repeat this until the quotient is less than the next number.
  4. write together the last quotient with the previous reminders.

For example n=45

45/2 .......    r_2=1, q_2=22
22/3 .......    r_3=1, q_3=7
 7/4 .......    r_4=3, q_4=1

since q4 = 1 is less than the next number i.e. 5, we break.

the result is q4r4r3r2 where it is equal to 1311.

Thank you for your help.

I did this but it does not work

n = 45;
i = 2;
list = {Mod[n, i]};

While[Quotient[n, i] >= i + 1, n == Quotient[n, i]; i++; 
   AppendTo[list, Mod[n, i]];
   If[Quotient[n, i] < i + 1, Break[]]; AppendTo[list, Quotient[n, i]]];

list
Row[Reverse[list]]

which gives

{1, 0, 15, 1, 11, 0, 9, 3, 7, 3}
Row[{3, 7, 3, 9, 0, 11, 1, 15, 0, 1}]

where it is not my desired result.

Was it helpful?

Solution

This is the code:

A = Table[i, {i, 2, 10}]; (* array of numbers *)
n = 45; (* initial value *)
ans = {}; (* future answer which is now empty list *)
For[i = 1, i <= Length[A], i++, (* looping over A *)
 If[n < A[[i]], (* exit condition *)
  ans = Append[ans, n]; (* appending last n when exit *)
  Break[]
  ];
 qr = QuotientRemainder[n, A[[i]]]; (* calculating both quotient and reminder *)
 ans = Append[ans, qr[[2]]]; (* adding second member to the answer *)
 Print[qr]; (* printing *)
 n = qr[[1]]; (* using first member as new n to process *)
 ];
ans (* printing result in Mathematica manner *)

It gives

{1, 1, 3, 1}

OTHER TIPS

You might use something like this:

f[n_Integer] := 
 NestWhileList[
   {QuotientRemainder[#[[1, 1]], #[[2]] + 1], #[[2]] + 1} &,
   {{n}, 1},
   #[[1, 1]] != 0 &
 ] // Rest

f[45]
{{{22, 1}, 2}, {{7, 1}, 3}, {{1, 3}, 4}, {{0, 1}, 5}}

You can use Part to get whatever bits of the output you desire.

Here's a somewhat more advanced way if you can handle the syntax:

f2[n_Integer]    := Reap[f2[{n, 0}, 2]][[2, 1, 2 ;;]] // Reverse

f2[{q_, r_}, i_] := f2[Sow @ r; QuotientRemainder[q, i], i + 1]

f2[{0, r_}, i_]  := Sow @ r

f2[45]
{1, 3, 1, 1}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top