Hello,

I thought I'd share a simple program to determine the number of set bits in a base ten number. This is useful to me as I need to group numbers based on the number of ones in them for the Quine-McCluskey method of reducing Boolean functions. Although one can do 4 bit numbers in one's head easily, its nice to double check quickly and if a 5 bit number is needed it could be more helpful then. I may continue with the idea and try to program the whole method. Anyway, it was fun to do.

EXPORT numSetBits(n)

// Oct 2013

// return the number of ones in n

BEGIN

LOCAL i := 0; //index of ones

LOCAL defB := Base; //save default base

LOCAL binB := 0; //binary base

LOCAL bVal := 0; //conversion to binaryBase := binB;

bVal := R→B(n);WHILE bVal≠0 DO

i:=i+1;

bVal:= bVal AND bVal-#1b;

END;//set default base to original val

Base := defB;RETURN i;

END;

Note:

I don't know how to format the following text here ...

"→" is actually "->" as in R->B(n);Enter a number onto the stack and execute the program and it will return the number of ones in the binary value."≠" is actually the "does not equal" symbol. (bVal!=0 doesn't work either one must use the Prime key it seems)

15

ENTER

numSetBits()

ENTER

4

6

ENTER

numSetBits()

ENTER

2

#15d = #1111b ... 4 ones

#6d = #110b ... 2 ones

If anyone sees some improvements I could make, please let me know as I'm new to Prime programming.

*Edited: 22 Oct 2013, 1:53 a.m. *