Largest number that is not a perfect square in MATLAB


Largest number that is not a perfect square
Given n integers, find the largest number is not a perfect square.

Example:

Input : arr[] = {16, 20, 25, 2, 3, 10}

Output : 20

Explanation: 20 is the largest number

that is not a perfect square



Input : arr[] = {36, 64, 10, 16, 29, 25}

Output : 29


Algorithm:

Step 1:

Take inputs from the user

Step 2:

Create 1 another array which contains one the elements which are not perfect square number.

Step 3:

Sort the array and get the highest number which is not a perfect square.


MATLAB CODE:

x=input('Enter the array:');
a=sqrt(x);
Y=[];
z=ceil(a);
y=a-z;
for i=1:length(x)
    if(y(i)~=0)
        Y=[Y x(i)];
    end
end
o=sort(Y);
disp(o(length(Y)));


OUTPUT:

Explanation of the code:

JAVA Code:


import java.util.Scanner;
import java.lang.Math;
class As
{
public static void main(String args[])
{
Scanner obj=new Scanner(System.in);
System.out.println("Enter the array length:");
int n=obj.nextInt();
int a[]=new int[n];
double z=0;
double mo=0;
for(int i=0;i<n;i++)
{
System.out.println("Enter the number in array:");
a[i]=obj.nextInt();
}
int l=0;
for(int i=0;i<n;i++)
{
z=Math.sqrt(a[i]);
mo=Math.ceil(z);
if ((z-mo)!=0)
{
l=l+1;
}
}
int d[]=new int[l];
int k=0;
for(int i=0;i<n;i++)
{
z=Math.sqrt(a[i]);
mo=Math.ceil(z);
if ((z-mo)!=0)
{
d[k]=a[i];
k=k+1;
}
}
int temp=0;
for(int i=0;i<l-1;i++)
{
for(int j=0;j<l-1-i;j++)
{
if(d[j]<d[j+1])
{
temp=d[j];
d[j]=d[j+1];
d[j+1]=temp;
}
}
}
System.out.println("The largest number which is not a perfect square number is:"+d[0]);
}
}

Output:

Reference video:

Algorithm to check a number is perfect square or not:


 

No comments