function [z1] = pfact(Z)
if Z>=2
p = 2:Z;
q = mod(Z,p);
a=find(q==0);
z1=p(a)
elseif Z==1
z1 = 1
elseif Z==0
z1 = []
disp("error")
end
I'm trying to get only prime factors but this code gives me all the factors, I need the prime factors that when they multiply with each other they give the original number.

댓글 수: 3

Dyuman Joshi
Dyuman Joshi 2023년 4월 2일
It's not clear to me as to what you want to do.
Say Z is 20, what should be the output then?
Daabir Momin
Daabir Momin 2023년 4월 2일
Z should be [2,2,5] , but I'm confused as to how I should approach the solution without using the factor function.
function [z1] = pfact(Z)
if Z>=2
p = 2:Z;
q = mod(Z,p);
a=find(q==0);
z1=p(a)
elseif Z==1
z1 = 1
elseif Z==0
z1 = []
disp("error")
end
pfact(20)
This gives me all the factors, can someone help me manipulate this code so it gives only the prime factors that when mutiplied together it gives you the original number.
like 20 should give output of [2,2,5]

댓글을 달려면 로그인하십시오.

답변 (1개)

Dyuman Joshi
Dyuman Joshi 2023년 4월 3일

0 개 추천

The code you wrote gives the divisors of Z.
This should work well unless you are dealing with extremely large numbers -
out1=pfact(20)
out1 = 1×3
2 2 5
out2=pfact(prod(primes(15)))
out2 = 1×6
2 3 5 7 11 13
function [z1] = pfact(Z)
if Z>=2
p = primes(sqrt(Z));
z1 = [];
while Z>1
d = p(rem(Z,p)==0);
if isempty(d)
z1=[z1 Z];break
end
z1=[z1 d];
Z = Z/prod(d);
end
z1=sort(z1);
elseif Z==1
z1 = 1;
elseif Z==0
z1 = [];
disp("error")
end
end

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2023년 4월 2일

답변:

2023년 4월 3일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by