编写3个shell编程用for,while,until求1…100的素数和

编写3个shell编程用for,while,until求1…100的素数和,第1张

按照你的要求编写的三个Bash程序如下

sum=0

for ((i=1i<=100i++))

do

for ((j=2j<ij++))

do

if ((i%j==0))

then

break

fi

done

if ((i==j))

then

sum=$[$sum+$i]

fi

done

echo $sum

源代码

运行结果

i=1

sum=0

until [[ i -gt 100 ]]

do

j=2

until [[ j -gt i-1 ]]

do

if ((i%j==0))

then

break

fi

let j++

done

if ((i==j))

then

sum=$[$sum+$i]

fi

let i++

done

echo $sum

源代码

运行结果

i=1

sum=0

while [[ i -le 100 ]]

do

j=2

while [[ j -lt i ]]

do

if ((i%j==0))

then

break

fi

let j++

done

if ((i==j))

then

sum=$[$sum+$i]

fi

let i++

done

echo $sum

源代码

运行结果

程序清单如下:

L0.2 prime.sh

#!/bin/bash

#

# SCRIPT: prime.sh

# AUTHOR: Zhaing&Bo

# DATE: 2010-11-21

# REV:1.1.A

#

# PLATFORM: Linularis

#

# PURPOSE: Read a number from the console, then print all the primes

# in (1~100). And at the same time calculate the sum of all

# the primes.

#

# set -n # Uncomment to check your syntax, without execution.

# # NOTE: Do not forget to put the comment back in or

# # the shell script will not execute!

# set -x # Uncomment to debug this shell script (Bash only)

#

##########################################################

########### DEFINE FILES AND VARIABLES HERE ##############

##########################################################

num=0 # 用来暂存用户输入整数

i=0# 循环控制变量(控制is_prime函数中的循环次数)

N=0# 待测值(is_prime函数形参)

n=0# 主函数循环控制变量(is_prime函数实参)

flag=1 # 素数表示(其中 1 表示是,0 表示否)

sum=0 # 用来存储素数之和

##########################################################

############### DEFINE FUNCTIONS HERE ####################

##########################################################

#/**

# * 函数名称:is_prime()

# * 函数功能:测试一个数是否为素数

# */

function is_prime() {

N=$1

flag=1

for ((i=2i<(N/2+1)i++)) {

((N%i))

if [ $? -ne 0 ]then

flag=0break

fi

}

}

##########################################################

################ BEGINNING OF MAIN #######################

##########################################################

# 输出提示

read -p "Please input a postive integer:" num

#echo -e "\nYour Number is: $num.\n"# 将用户输入输出,以便用户确定

echo -e "All the prime from 1 to $num: "

for ((n=2n<=$numn++)) {

is_prime n

if [ $flag -eq 1 ]then

echo -n "$n "

((sum=sum+n))

# echo -e "$n Is prime."

# else

# echo -e "$n is Not prime.\n"

fi

}

# 输出所有素数的和(1~num)

echo -e "\nThe SUM of all the primes is: $sum.\n"

# End of script

您好!脚本如上所示,我只在Fedora13下进行过测试,没有问题;但,别的Linux平台我不敢保证程序能够正常运行。注意,其中汉语注释在Linux下可能显示乱码,本人不再为此提供技术支持。

另外,这也是我写的第一个脚本。程序可能不是最好的,有什么问题请留言。

这类小脚本并不是很难,多查查书,google一下基础概念;自己就能写出来的。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/8119906.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-13
下一篇 2023-04-13

发表评论

登录后才能评论

评论列表(0条)

保存