代码
# !/bin/bash # 计算一个十进制整数的二进制表示中1的个数 getnum(){ if [ - z " $1 " ] then echo " Usage:$(basename " $0 " )需要一个参数 " return - 1 fi a = " $1 " num = 0 while [ $a -ne 0 ] do ((a &= (a - 1 ))) ((num ++ )) done echo " `toBin $1`中1的个数为${num} " } # 将一个十进制整数用二进制表示 toBin(){ b = " $1 " i = 0 while [ " $b " -ne 0 ] do ((arr[i ++ ] = $b & 1 )) ((b >>= 1 )) done for ((j = i;j >= 0 ;j -- )) do echo - n $ {arr[j]} done echo } # 求给定值n以内所有的素数 getPrime(){ array = ( $ (seq 2 $1 )) for ((m = 0 ;m ** 2 < " $1 " ;m ++ )) do for ((n = m + 1 ;n< " $1 " - 1 ;n ++ )) do if [[ $ {array[m]} -ne 0 && $ {array[n]} -ne 0 ]] then if [ $ (( $ {array[n]} %$ {array[m]})) -eq 0 ] then ((array[n] = 0 )) fi fi done done echo " $1以内的素数为: " for ((k = 0 ;k< " $1 " - 1 ;k ++ )) do if [ $ {array[k]} -ne 0 ] then printf " %s " " ${array[k]} " fi done echo} # main getnum $1 getPrime $1