Let's see how *humans* convert numbers to binary.

1) We divide the number x by 2 to the power of n and take its remainder from dividing by 2.

\(\Bigl\lfloor\dfrac{x}{2^{n}}\Bigr\rfloor\operatorname{mod}2=\lfloor2^{-n}x\rfloor \operatorname{mod} 2\)

We may also need the length of the binary x, so it can be obtained by the formula:

\(\lceil log_2x\rceil\)

2) When we have all remainders we concatenate them with each other. In math, we can replace concatenation with \(a*10^n+b*10^{n+1}+c*10^{n+2}...\)

3) Write all remainders in reversed order

So here's the formula that converts decimal to binary.

\(bin(x)=\sum^{\lceil\operatorname{log}_2x\rceil}_{n=0}\lfloor2^{-n}x\rfloor\operatorname{mod}2*10^n\)

Look at this in Desmos: https://www.desmos.com/calculator/2jabzvxn4t

JoshuaGreen Oct 3, 2019

#1**0 **

JG: That is very nice. Since you have a good understanding of deriving mathematical formulas, it would serve you very well to learn a programming language such as Python, C, C++.......etc. You could, for instance, program the above formula using very short one-line code to convert any number into binary, almost instantly, such as this line: n=123456789;m=2; a=n%m;printa,", ",;b=int(n/m);n=b;if(n>m, goto2, discard=0;printb,;

It will instantly convert 123456789 into binary like this:

1 , 0 , 1 , 0 , 1 , 0 , 0 , 0 , 1 , 0 , 1 , 1 , 0 , 0 , 1 , 1 , 1 , 1 , 0 , 1 , 1 , 0 , 1 , 0 , 1 , 1 , 1 [read from right to left].

Guest Oct 3, 2019

#2**0 **

Thanks for your reply. I want to say that I already know Python and Javascript, and I know how to convert decimal numbers to binary using programming, but I'm interested in doing this mathematically.

JoshuaGreen
Oct 3, 2019

#3**+1 **

That's really cool!!

If you want to try it, here's another (similar, maybe easier) challenge:

Make a function that will return the sum of the digits. So for examples:

f(123) = 6

f(100) = 1

f(4532) = 14

f(3) = 3

f(0) = 0

And let's also assume here that n ≤ 32

hectictar Oct 3, 2019

#5**+1 **

\(f(x)=\sum^{\lfloor\log_{10}x\rfloor}_{n=0}\Bigl\lfloor\dfrac{x}{10^n}\Bigr\rfloor\operatorname{mod}10\)

look at this in Desmos: https://www.desmos.com/calculator/6tktu9vizl

JoshuaGreen
Oct 3, 2019

#4**+1 **

Hi hectictar: Just for my own curiosity, I took up you suggestion and hastily wrote this very short code to sum up the digits of any number. It can easily add up the first 1,000 digits of Pi, for example. In this short code, it sums up:123456789 and counts them as well:

n=123456789;s=0;p=0;cycle: s=s+(n%10);p=p+1;n=int(n/10);if(n!=0, goto cycle,0);print"Total Sum =",s;print"Total Num =",p

Total Sum = 45

Total Num = 9

Guest Oct 3, 2019