Perfect Square in Matlab

41 ビュー (過去 30 日間)
Zaid
Zaid 2022 年 7 月 4 日
編集済み: Siraj 2022 年 7 月 4 日
What is the most efficient way to check wether a number is a perfect square or not in matlab. Perfect square are 4,9,16 and so on

採用された回答

Siraj
Siraj 2022 年 7 月 4 日
編集済み: Siraj 2022 年 7 月 4 日
Hi,
It is my understanding that you want to know the easiest way to find whether a number is a perfect square or not.
For this first you can take the square root of the number and then see if the square root is a proper integer or not. We know that any integer when divided by one leaves zero as the remainder, therefore we can use the “modulo” function to find the remainder of the square root when divided by one and if the remainder is zero means that the number is a perfect square.
Refer to the documentation for more on modulo function in MATLAB.
n = 49;
%take the square root
sq_rt = sqrt(n);
% now check if the sq_rt is a proper integer or not
int_or_not = mod(sq_rt,1);
if(int_or_not == 0)
disp("Prefect Square");
else
disp("Not a Perfect Square");
end
Prefect Square

その他の回答 (3 件)

Chunru
Chunru 2022 年 7 月 4 日
x = (1:20);
mod(sqrt(x), 1) == 0
ans = 1×20 logical array
1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0

Karan Kannoujiya
Karan Kannoujiya 2022 年 7 月 4 日
Hi Zaid,
You can use below code to check for a perfect square-->
%num---> number you want to check
y=sqrt(num);
z=ceil(y);
if(z==y)
disp('The number is perfect square number');
else
disp('The number is not a perfect square number');
end

Shivam Lahoti
Shivam Lahoti 2022 年 7 月 4 日
you can check for perfect square by using the following check, however representable number might sparse if n is large enough.
if floor(sqrt(n)).^2 == n

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by