How to resolve the algorithm Pernicious numbers step by step in the Forth programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Pernicious numbers step by step in the Forth programming language
Table of Contents
Problem Statement
A pernicious number is a positive integer whose population count is a prime. The population count is the number of ones in the binary representation of a non-negative integer.
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pernicious number.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Pernicious numbers step by step in the Forth programming language
Source code in the forth programming language
: popcount { n -- u }
0
begin
n 0<>
while
n n 1- and to n
1+
repeat ;
\ primality test for 0 <= n <= 63
: prime? ( n -- ? )
1 swap lshift 0x28208a20a08a28ac and 0<> ;
: pernicious? ( n -- ? )
popcount prime? ;
: first_n_pernicious_numbers { n -- }
." First " n . ." pernicious numbers:" cr
1
begin
n 0 >
while
dup pernicious? if
dup .
n 1- to n
then
1+
repeat
drop cr ;
: pernicious_numbers_between { m n -- }
." Pernicious numbers between " m . ." and " n 1 .r ." :" cr
n 1+ m do
i pernicious? if i . then
loop
cr ;
25 first_n_pernicious_numbers
888888877 888888888 pernicious_numbers_between
bye
You may also check:How to resolve the algorithm Repeat a string step by step in the Explore programming language
You may also check:How to resolve the algorithm Window creation/X11 step by step in the Raku programming language
You may also check:How to resolve the algorithm Joystick position step by step in the Delphi programming language
You may also check:How to resolve the algorithm Multiple regression step by step in the Python programming language
You may also check:How to resolve the algorithm Order two numerical lists step by step in the Lua programming language