Number of 1's in binary expansion of n: Difference between revisions

From Rosetta Code
Content added Content deleted
(Blanked the page)
No edit summary
Line 1: Line 1:
{{Draft task}}

;Task: Calculate number of 1's in binary expansion of '''n''', where '''n <= 50'''

<br><br>

=={{header|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>
{{out}}
<pre>
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...
</pre>

Revision as of 10:18, 25 June 2021

Number of 1's in binary expansion of n is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.
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...