Number of 1's in binary expansion of n
Redirect page
Redirect to:
- Task
- Calculate number of 1's in binary expansion of n, where n <= 50
Ring
<lang ring> load "stdlib.ring" see "working..." + nl see "Number of 1's in binary expansion of n:" + nl
row = 0 limit = 50
for n = 1 to limit
onesum = 0 bin = decimaltobase(n,2) for m = 1 to len(bin) if bin[m] = "1" onesum = onesum + 1 ok next see "" + onesum + " " row = row + 1 if row%5 = 0 see nl ok
next
see "done..." + nl
func decimaltobase(nr,base)
decList = 0:15 baseList = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"]
binList = [] binary = 0 remainder = 1 while(nr != 0) remainder = nr % base ind = find(decList,remainder) rem = baseList[ind] add(binList,rem) nr = floor(nr/base) end binlist = reverse(binList) binList = list2str(binList) binList = substr(binList,nl,"") return binList
</lang>
- Output:
working... Number of 1's in binary expansion of n: 1 1 2 1 2 2 3 1 2 2 3 2 3 3 4 1 2 2 3 2 3 3 4 2 3 3 4 3 4 4 5 1 2 2 3 2 3 3 4 2 3 3 4 3 4 4 5 2 3 3 done...