假设我们有以下用于素数分解的脚本
z=input('enter your number : ');
for ii=2:z
s=0;
while z/ii==floor(z/ii) % check if z is divisible by ii
z=z/ii;
s=s+1;
end
if s>0
str = [num2str(ii) '^' num2str(s) ];
disp(str) ;
% If z = 1, no more divisions are necessary,
% thus breaks the loop and quits
if z == 1
break
end
end
end
但此代码的输出格式不正确,例如
>> integer_factorization
enter your number : 30
2^1
3^1
5^1
我怎么能这样做才能得到
30=2^1*3^1*5^1?
提前致谢
答案 0 :(得分:2)
这非常简单:使用fprintf(''); instead打印/显示因子。
z=input('enter your number : ');
ans='' %the final answer string
for ii=2:z
s=0;
while z/ii==floor(z/ii) % check if z is divisible by ii
z=z/ii;
s=s+1;
end
if s>0
str = [num2str(ii) '^' num2str(s) ];
%disp(str) ;
strcat(ans,'*',str); %concats the * str as per requirement.
% If z = 1, no more divisions are necessary,
% thus breaks the loop and quits
if z == 1
break
end
end
end
ans=ans(2:end); % to remove the first *
fprintf(ans); % can even use the disp() function.
所以,基本上,添加了一个字符串来将因子附加到其中并显示在循环之外的末尾。
答案 1 :(得分:1)
您可以简单地创建一个字符串并将您的数字添加到字符串中,最后打印字符串。如下:
z=input('enter your number : ');
for ii=2:z
s=0;
while z/ii==floor(z/ii) % check if z is divisible by ii
z=z/ii;
s=s+1;
end
if s>0
str = str + [num2str(ii) '^' num2str(s) '*' ];%only update
% If z = 1, no more divisions are necessary,
% thus breaks the loop and quits
if z == 1
break
end
end
str = str(0,str.size -1) %use proper command to remove the last * from your string result
disp(str) ; %display the str at the end in one line
end
答案 2 :(得分:1)
Litle修改你的代码。
z=input('enter your number : ');
for ii=2:z
s=0;
while z/ii==floor(z/ii) % check if z is divisible by ii
z=z/ii;
s=s+1;
end
if s>0
str += [num2str(ii) '^' num2str(s) ];
% If z = 1, no more divisions are necessary,
% thus breaks the loop and quits
if z == 1
break
else
str+='*';
end
end
end
disp(str);
答案 3 :(得分:1)
这可行!只需对代码进行一些更改
wheel
答案 4 :(得分:1)
首先感谢大家的支持,这是我的最终解决方案
z=input('enter your number : ');
string='';
for ii=2:z
s=0;
while z/ii==floor(z/ii) % check if z is divisible by ii
z=z/ii;
s=s+1;
end
if s>0
str =[num2str(ii) '^' num2str(s) ];
string=strcat(string,str);
string= strcat(string,'*');
% If z = 1, no more divisions are necessary,
% thus breaks the loop and quits
if z == 1
break
end
end
end
string=string(1:end-1);% remove last sign of multiplicaiton
fprintf('prime factorization is %s\n',string);
这里有几个例子
>> integer_factorization
enter your number : 30
prime factorization is 2^1*3^1*5^1
另一个
>> integer_factorization
enter your number : 35
prime factorization is 5^1*7^1
和最后一个
>> integer_factorization
enter your number : 100
prime factorization is 2^2*5^2