CS99

Summer 2002

HW5 Solutions

 

1.       Perfect and not-so perfect numbers
Part A: perfect.m
Solution 1.
clear all;

p = input(‘Enter a number: ‘);

sumOfDivisors = 0;
for divisor = 1 : ( p – 1)
        if ~mod( p, divisor )
           sumOfDivisors = sumOfDivisors + divisor;

        end
end


if sumOfDivisors < p
        disp( [ num2str( p ) ‘ is deficient.’] );
elseif sumOfDivisors > p
        disp( [ num2str( p ) ‘ is abundant.’ ] );
else
        disp( [ num2str( p ) ‘ is perfect.’ ] );
end

Solution 2.
clear all;
p = input(‘Enter a number: ‘);
%16384 if the maximum array size in the Student Edition of MATLAB
sumOfDivisors = 0;
for startInterval = 1: 16384 : (p –1)
        divisors = startInterval: min( startInterval + 16384 – 1, p – 1 );
        sumOfDivisors = sumOfDivisors + sum( divisors.*(mod(p, divisors) == 0 ) ) ;
end


if sumOfDivisors < p
        disp( [ num2str( p ) ‘ is deficient.’] );
elseif sumOfDivisors > p
        disp( [ num2str( p ) ‘ is abundant.’ ] );
else
        disp( [ num2str( p ) ‘ is perfect.’ ] );
end

Part B: allperfects.m
Solution 1.
clear all;

disp(‘This solution will display all perfect numbers in the range [2, <Your Number>].’);
p = input(‘Enter a number: ‘);
for n = 2: p
        sumOfDivisors = 0;
        for divisor = 1 : ( n – 1)
            if ~mod( n, divisor )
               sumOfDivisors = sumOfDivisors + divisor;

           end
        end

       
if sumOfDivisors == n
           disp( [ num2str( n ) ‘ is perfect.’ ] );
        end

end

Solution 2.
clear all;

disp(‘This solution will display all perfect numbers in the range [2, <Your Number>].’);
p = input(‘Enter a number: ‘);
for n = 2: p
        %16384 if the maximum array size in the Student Edition of MATLAB
        sumOfDivisors = 0;
        for startInterval = 1: 16384 : (p –1)
            divisors = startInterval: min( startInterval + 16384 – 1, p – 1 );
            sumOfDivisors = sumOfDivisors + sum( divisors.*(mod(p, divisors) == 0 ) ) ;
        end

       
if sumOfDivisors == n
           disp( [ num2str( n ) ‘ is perfect.’ ] );
        end

end

2.       Quirk-some squares
Solution 1.
%quirksome.m
clear all;
fprintf(‘The four digit quirky squares are: \n’);
for num = 0:9999
      %split the number in 2
      front = floor( num/100 );
      back = mod( num, 100 );
      %add the square of the sum of the front and back and compare with the original
      if ( ( front + back )^2 == num )
         fprintf(‘%d = (%d + %d)^2\n’, num, front, back);
      end
end

Answers: 0000, 0001, 2025, 3025, 9801

Solution 2.
%quirksome.m
clear all;
numbers = 0:9999;
front = floor( numbers/100 );
back = mod( numbers, 100 );
numbers = numbers( (front + back).^2 == numbers );
disp([‘The four digit quirky numbers are: ‘ num2str( numbers ) ] );