MATLAB Answers

how do i check if a number is a prime number, a square, and or a factor of 6?

56 views (last 30 days)
Vjon Joson
Vjon Joson on 1 Apr 2020
Commented: Walter Roberson on 2 Apr 2020
here is the current idea for the code so far
integer = 4;
if % ** check if integer is a prime **
Prime = integer % => If condition is met
elseif % ** check if the number is square **
Square = integer % => Else condition is met
elseif % chekc if divisible by 6
Factorof6=integer
end

Accepted Answer

Birdman
Birdman on 1 Apr 2020
n=4;
%check if number is prime
isprime(n) %returns logical value
%check if number is square
mod(numel(factor(n)),2)==0 %returns logical value
%check if number is divisible by 6
mod(n,6)==0 %returns logical value
  4 Comments
Walter Roberson
Walter Roberson on 2 Apr 2020
yup, checking the square root is much clearer ;-)
Another form of checking:
if floor(sqrt(n)).^2 == n
This does have difficulties when n is large enough that adjacent representable numbers get sparse.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by