Prime
Factors  a Matlab script
This program lists the prime
factors (PFs) of an integer. It will test neither 0 nor 1.
It is well known that PFs of a positive integer are the primes that
divide into that integer exactly,
without leaving a remainder. The process of finding these numbers is
called integer
factorization, or prime
factorization.
Matlab has some functions for this purpose, too.
Here’s the full Matlab script:
%
Clears
variables and screen
clear;
clc
%
Asks
user for input
z
= input('Enter
your
positive number: ');
%
Loops to
test all integers (2 through z) as PFs
for
i = 2 : z
s
= 0;
%
Is z/i an integer? Is the
remainder 0?
while
z/i == floor(z/i)
z = z/i;
s = s + 1;
end
%
A PF is found and
displayed
if
s > 0
str = [num2str(i) '^'
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
Example
1:
What are the prime factors of 49?
Run the code above and
enter your number…
Enter your positive
number: 90
Matlab answer is
2^1
3^2
5^1
This
means that 90 = 2 x 3^{2} x 5
Example
2:
Enter your positive number: 390
2^1
3^1
5^1
13^1
This means that 390 = 2 x
3 x 5 x 13
Matlab has at least 3 builtin functions related to PFs.
a) 'factor(x)' returns a
vector containing the PFs of x.
For example:
factor(390), results in
ans =
2
3
5
13
b) 'primes(x)' is a row
vector of the primes less than or
equal to x.
For example:
primes(10), results in
ans =
2
3
5
7
c) 'isprime(x)' is true
for prime numbers. For example:
isprime(10) results in
ans =
0
From
'Prime Factors' to
home
From
'Prime
Factors' to Matlab Cookbook
