echo "Enter A Number: "
read num
show=`expr $num`
flag=1
square=`expr $num \* $num`
while [ $num -gt 0 ]
do
flag1=`expr $num % 10`
flag2=`expr $square % 10`
if [ $flag1 -ne $flag2 ]
then
flag=0
break
fi
num=`expr $num / 10`
square=`expr $num / 10`
done
if [ $flag -eq 0 ]
then
echo $show "is NOT An Automorphic Number"
else
echo $show "is An Automorphic Number"
fi
这是检查自同数的代码。基本上这些数字出现在其平方数的末尾。就像 25 留在 625 的末尾。
它仅适用于输入 5。它不适用于 25、76 等。我哪里出错了?
答案1
因为我不喜欢bash
算术,所以我编写了awk
进行检查的示例程序:
{len=length($1);
pow=$1 * $1;
div= 10^len;
if ($1 == pow % div) print $1 " is An Automorphic Number";
else print $1 " is not An Automorphic Number"}
它只关心输入数字的长度并进行相应的设置。这是我的测试:
[ ~]$ echo 1 |awk '{len=length($1);pow=$1 * $1; div= 10^len; if ($1 == pow % div) print $1 " is An Automorphic Number"; else print $1 " is not An Automorphic Number"}'
1 is An Automorphic Number
[ ~]$ echo 5 |awk '{len=length($1);pow=$1 * $1; div= 10^len; if ($1 == pow % div) print $1 " is An Automorphic Number"; else print $1 " is not An Automorphic Number"}'
5 is An Automorphic Number
[ ~]$ echo 76 |awk '{len=length($1);pow=$1 * $1; div= 10^len; if ($1 == pow % div) print $1 " is An Automorphic Number"; else print $1 " is not An Automorphic Number"}'
76 is An Automorphic Number
答案2
太长了;博士
您不妨只打印以下数字是自守:
$ printf '%s\n' 11 5 25 625 76 111 12890625>infile
$ awk '{s=$0^2; r=$0"$"};s~r' infile
5
25
625
76
12890625
或者,以更神秘的形式:
$ awk '$0^2 ~ $0"$"' infile
或者,如果您想要每个数字的明确答案:
$ awk '{out=" NOT "} $0^2 ~ $0"$" {out=" "} {printf "%20s %s%s",$0,"is"out"An Automorphic Number",ORS}' infile
11 is NOT An Automorphic Number
5 is An Automorphic Number
25 is An Automorphic Number
625 is An Automorphic Number
76 is An Automorphic Number
111 is NOT An Automorphic Number
12890625 is An Automorphic Number
以前的解决方案。
您可能只需检查正方形的尾部部分是否与n
数字匹配。
#!/bin/bash
n=${1:-625}
square=$((n * n))
[[ $square =~ $n$ ]] && itis="" || itis="NOT"
echo "$n is $itis An Automorphic Number"
关于你的脚本
您的脚本存在几个问题。
一般来说,您应该使用算术扩展而不是非常旧的
expr
.将输入数字定义为脚本的参数会更容易。
的变化
square
也应该是square
:square=$((square/10))。不是square=$((num/10))
你拥有的。
进行一些更改,您的脚本将变为:
#!/bin/bash
n=${1:-625}
flag=1
square=$((n * n))
num=$n
echo "Testing =$num= and square =$square="
while [ $num -gt 0 ]
do
flag1=$(($num % 10))
flag2=$(($square % 10))
echo "Testing +$num+ with +$square+ that generate =$flag1= and =$flag2="
if [ $flag1 -ne $flag2 ]
then
flag=0
break
fi
num=$((num / 10))
square=$((square / 10))
done
if [ $flag -eq 0 ]
then
echo "$n is NOT An Automorphic Number"
else
echo "$n is An Automorphic Number"
fi
你会这样称呼它:
$ ./script 625
625 is An Automorphic Number
$ ./script 76
76 is An Automorphic Number
$ ./script 111
111 is NOT An Automorphic Number