- 论坛徽章:
- 60
|
本帖最后由 reyleon 于 2018-08-01 17:03 编辑
gawk 4.0+, 主要用到了 gawk 4.0+ 版本 asorti 函数排序的特性
[root@hk ~]# cat f.awk
function rec(n) {
v=1;
t=split(n,a,"");
for(i=1;i<=t;i++) v*=a;
if(v==n)return s;
s=s?s" - "v:v;
rec(v);
}
{
for(k=1;k<=$1;k++){ s="";x=sprintf("%s - %s",k,rec(k));L=split(x,b);c[L]=c[L]?c[L]"\n"x:x }
# 这里排序选最大长度
asorti(c,d,"@ind_num_desc");
print c[d[1]];
}
[root@hk ~]# echo 100 | awk -f f.awk
77 - 49 - 36 - 18 - 8
[root@hk ~]#
[root@hk ~]# echo 1000 | awk -f f.awk
679 - 378 - 168 - 48 - 32 - 6
688 - 384 - 96 - 54 - 20 - 0
697 - 378 - 168 - 48 - 32 - 6
769 - 378 - 168 - 48 - 32 - 6
796 - 378 - 168 - 48 - 32 - 6
868 - 384 - 96 - 54 - 20 - 0
886 - 384 - 96 - 54 - 20 - 0
967 - 378 - 168 - 48 - 32 - 6
976 - 378 - 168 - 48 - 32 - 6
[root@hk ~]# echo 10000 | awk -f f.awk
6788 - 2688 - 768 - 336 - 54 - 20 - 0
6878 - 2688 - 768 - 336 - 54 - 20 - 0
6887 - 2688 - 768 - 336 - 54 - 20 - 0
7688 - 2688 - 768 - 336 - 54 - 20 - 0
7868 - 2688 - 768 - 336 - 54 - 20 - 0
7886 - 2688 - 768 - 336 - 54 - 20 - 0
8678 - 2688 - 768 - 336 - 54 - 20 - 0
8687 - 2688 - 768 - 336 - 54 - 20 - 0
8768 - 2688 - 768 - 336 - 54 - 20 - 0
8786 - 2688 - 768 - 336 - 54 - 20 - 0
8867 - 2688 - 768 - 336 - 54 - 20 - 0
8876 - 2688 - 768 - 336 - 54 - 20 - 0
[root@hk ~]#
------------------------
代码重发下, 上面的代码 因为CU会隐藏掉[i ]:
[root@hk ~]# cat f.awk
function rec(n) {
v=1;
t=split(n,a,"");
for(p=1;p<=t;p++) v*=a[p];
if(v==n)return s;
s=s?s" - "v:v;
rec(v);
}
{
for(k=1;k<=$1;k++){ s="";x=sprintf("%s - %s",k,rec(k));L=split(x,b);c[L]=c[L]?c[L]"\n"x:x }
asorti(c,d,"@ind_num_desc");
print c[d[1]];
}
------------------
再次更新, 以下是经过优化的代码, 一千万的计算大概花了 1分多钟, 比上面最原始的快了 NNNNNNN 倍... 基本上与3楼的代码 相当, 稍慢一丢丢
[root@hk ~]# time echo 10000000 | awk -f f.awk > /tmp/1qw
real 1m35.637s
user 1m35.521s
sys 0m0.082s
[root@hk ~]# cat f.awk
function rec(n) {
v=1;
t=split(n,a,"");
for(p=1;p<=t;p++) v*=a[p];
if(v==n)return s;
s=s?s" - "v:v;
rec(v);
}
{
for(k=1;k<=$1;k++){
s="";x=sprintf("%s - %s",k,rec(k));L=split(x,b);c[L]=c[L]?c[L]"\n"x:x;
asorti(c,d,"@ind_num_desc");
var=c[d[1]];
delete c;
c[d[1]]=var;
}
print var;
}
[root@hk ~]# awk --version
GNU Awk 4.2.1, API: 2.0
Copyright (C) 1989, 1991-2018 Free Software Foundation.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/.
[root@hk ~]#
|
|