CS 99

Summer 2002: Lab 3                                                                               07.11

Solutions

 
1. Geometric Mean
%GeoMean.m
%Name: Trinity
%CUID: 303000
%Date: 11 July 2002
 
%clear workspace variables
clear all;

%Prompt user for values
disp(‘Enter a sequence of numbers, terminated by a negative value.’);
val = input('> ');
 
%initialize variables
count = 0;                %number of values entered by user
prod = 1;                  %running product of values
 
%update count and prod when input value is non-negative
while val >= 0   
   count = count + 1;
   prod = prod*val;
   %prompt user for next value
   val = input('> ');
end
 
%report results
if count > 0
   gMean = prod^(1/count);
   disp(['The geometric mean of the values is ' num2str( gMean ) ] );
else
   disp('No input data given');
end
 
2. Not a perfect square

%clear workspace variables
clear all;

%counter variable
n  = 1;
%true if we find an integral value for which the relation is a perfect square, false otherwise
foundSqr = 0;
 
while n <= 10000
   val = floor( n + sqrt(n) + 1/2 );
   %a number is a perfect square if its square root is an integer
   if floor( sqrt( val ) ) == ceil( sqrt( val ) )
      disp([ num2str( val ) ' is a perfect square! Whoa.' ]);
      foundSqr = 1;
   end
   n = n + 1;
end
 
%report results
if ~foundSqr
   disp('No perfect squares found');
end