How to resolve the algorithm Population count step by step in the Fortran programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Population count step by step in the Fortran programming language

Table of Contents

Problem Statement

The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:

For example,   5   (which is   101   in binary)   has a population count of   2.

Evil numbers   are non-negative integers that have an   even   population count. Odious numbers     are  positive integers that have an    odd   population count.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Population count step by step in the Fortran programming language

Source code in the fortran programming language

program population_count
  implicit none

  integer, parameter :: i64 = selected_int_kind(18)
  integer(i64) :: x
  integer :: i, n
    
  x = 1
  write(*, "(a8)", advance = "no") "3**i :"
  do i = 1, 30
    write(*, "(i3)", advance = "no") popcnt(x)
    x = x * 3
  end do

  write(*,*)
  write(*, "(a8)", advance = "no") "Evil :"
  n = 0
  x = 0 
  do while(n < 30)
    if(mod(popcnt(x), 2) == 0) then
      n = n + 1
      write(*, "(i3)", advance = "no") x
    end if
    x = x + 1
  end do

  write(*,*)
  write(*, "(a8)", advance = "no") "Odious :"
  n = 0
  x = 0 
  do while(n < 30)
    if(mod(popcnt(x), 2) /= 0) then
      n = n + 1
      write(*, "(i3)", advance = "no") x
    end if
    x = x + 1
  end do

contains

integer function popcnt(x)
  integer(i64), intent(in) :: x
  integer :: i

  popcnt = 0
  do i = 0, 63
    if(btest(x, i)) popcnt = popcnt + 1
  end do

end function
end program


  

You may also check:How to resolve the algorithm Minimum multiple of m where digital sum equals m step by step in the Java programming language
You may also check:How to resolve the algorithm Knapsack problem/0-1 step by step in the C++ programming language
You may also check:How to resolve the algorithm A+B step by step in the Furor programming language
You may also check:How to resolve the algorithm Prime decomposition step by step in the ERRE programming language
You may also check:How to resolve the algorithm Floyd's triangle step by step in the Tcl programming language