Hello readers! In this post, I want to share with you a simple program to count the number of perfect square between 2 numbers. For example, If I enter 2 numbers say 1 and 9, then it should give me the result as 3 since there are 3 perfect square numbers between 1 and 9, which are 1,4 and 9.This post was requested by one of our visitors 'Snehlata Tripathi' in a comment under one of our older post on how to "find the highest and lowest perfect square number of desired digits using MATLAB program".

In this post, I have prepared a simple matlab program which will initially ask for the the 2 numbers and then go on to check whether the number lying between them are perfect square or not. If any number is found to be perfect square, then the counter is incremented by one. At the end the value of counter is presented as the answer.

% program to count the number of perfect squares between 2 numbers

% Author: Amit Biswal @ Speaking Technology

% URL: http://amitbiswal.blogspot.com

clc

clear all

num=0;

n1=input('Input the smaller number:');

n2=input('Input the larger number:');

if n1>n2

fprintf('First number should be smaller than second!!\n Please Try Again')

elseif n1==n2

fprintf('The numbers are equal!!\n Please Try Again')

else

n0=n1;

while(n1<=n2)

root=sqrt(n1);

if root==fix(root)

num=num+1;

end

n1=n1+1;

end

fprintf('Number of perfect squares between %d and %d is %d',n0,n2,num)

end

Well, this program may not be the efficient one and there is always a room for improvement. So I welcome your feedback and efficient algorithms. If you have any query, doubt or suggestions, then you can comment below and let me know. Thankyou for reading!