gpt4 book ai didi

matlab - 简化查找阿姆斯壮数的代码

转载 作者:行者123 更新时间:2023-12-02 04:48:53 25 4
gpt4 key购买 nike

A armstrong number is a number that is the sum of its own digits each raised to the power of the number of digits.

我的代码如下所示,用于查找 7 位阿姆斯特朗号码,使用 bsxfun 的原因是它非常快,但它只接受三个参数(Mathematica 的类似函数 Outer 可以接受多个参数)。如何使我的代码更紧凑?

tic
m1=(1:9).^7;
m=(0:9).^7;
r1=bsxfun(@plus, m1', m);
r2=bsxfun(@plus, r1, reshape(m,1,1,[]));
r3=bsxfun(@plus, r2, reshape(m,1,1,1,[]));
r4=bsxfun(@plus, r3, reshape(m,1,1,1,1,[]));
r5=bsxfun(@plus, r4, reshape(m,1,1,1,1,1,[]));
r6=bsxfun(@plus, r5, reshape(m,1,1,1,1,1,1,[]));
r7= permute(r6, 7:-1:1);
A=reshape((1e6:1e7-1), size(r7));
A(A==r7)
toc

(*
ans =

1741725
4210818
9800817
9926315
*)

最佳答案

您可以使用 shiftdim 而不是 reshape 并将 bsxfun 放在 for 循环中

m=(0:9).^7.';
r=(1:9).^7.';
for k=1:6,
m = shiftdim(m,-1);
r = bsxfun(@plus, r, m);
end
r= permute(r, 7:-1:1);
A=reshape((1e6:1e7-1), size(r7));
A(A==r7)

关于matlab - 简化查找阿姆斯壮数的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19250906/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com