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

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

3 Kommentare

The combination to a safe is a four digit integer that:
• Is a perfect square*
• Is not divisible by 2, 3, or 5.
a. Write a function in MATLAB that takes one input and returns 1 if it is a perfect square, and 0 otherwise
https://www.mathworks.com/matlabcentral/answers/514501-how-do-i-check-if-a-number-is-a-prime-number-a-square-and-or-a-factor-of-6#comment_819187
Since the core answers are all basically already on this page, I'll just add that logical indexing, implicit casting, and implicit expansion can make this tidy.
x = 100:999; % a set of numbers as a row vector
issquare = ~mod(sqrt(x),1); % implicit binarization
ismultiple = ~mod(x,[2; 3; 5]); % implicit expansion
validnums = issquare & ~any(ismultiple,1); % logical combination of masks
x(validnums) % logical indexing
ans = 1×7
121 169 289 361 529 841 961
Now you have to make a function out of it.

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

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

7 Kommentare

>> mod(numel(factor(33)),2)
ans =
0
The test for square needs some work...
Editing for the square check:
n=33;
[~,A,~]=unique(factor(n));
all(mod(diff([A.' numel(factor(n))+1]),2)==0) %returns logical value
If returns 1, then the number is square number, if else, it is not.
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.
mod(numel(factor(136)),2)==0 is True, but 136 is not a square
Torsten
Torsten am 15 Okt. 2022
Bearbeitet: Torsten am 15 Okt. 2022
2*3 = 6, and 6 is not a square.
Yes, the answer given is incorrect.
mod(numel(factor(a)),2)==0 is not sufficient for "a" to be a square.
https://www.mathworks.com/matlabcentral/answers/514501-how-do-i-check-if-a-number-is-a-prime-number-a-square-and-or-a-factor-of-6#comment_819105 shows a revised test (which I did not examine)

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Operators and Elementary Operations finden Sie in Hilfe-Center und File Exchange

Gefragt:

am 1 Apr. 2020

Bearbeitet:

DGM
am 5 Jan. 2023

Community Treasure Hunt

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

Start Hunting!

Translated by