CS99

Summer 2002

HW6 Solutions

 

1.       Sisyphus, the Snail
clear all;
well_height  = input(‘Enter well height: ‘);
up = input(‘Enter distance snail can travel during day while rested: ‘);
down = input(‘Enter distance snail slides down at night: ‘);
fatigue = input(‘Enter the fatigue factor: ‘)/100;
curr_up = up;       %current climbing ability
curr_height = 0;      %current height of snail
day = 1;

fprintf(‘Calculating …’);
while curr_up >= 0
       curr_height = curr_height + curr_up;
      %has the snail climbed out of well? is it going to hit bottom later? if so, break
      if curr_height > well_height | curr_height < down
         break;
      end
      %at night, snail slides
       curr_height = curr_height – down;
       %calculate new climbing ability
      curr_up = curr_up – fatigue*up;
      day = day + 1;
end
%report results
if curr_height >= well_height
       fprintf(‘The snail climbs out on  day %d.’, day );
else
        fprintf(‘The snail is stuck in the well on day %d.’, day);
end

 

2.       Goldbach’s conjecture
Solution 1.
disp(‘
Please enter a sequence of even numbers, each greater or equal to 4. ‘);
n = input(‘> ‘);
while mod( n, 2 ) == 0 & n > 4
      p = primes( n );
       fprintf(‘%d’, n );
      pairs = 0;
      for k = 1 : length( p )
         for m = k : length( p )
             if p(k) + p(m) == n
                fprintf(‘ = %d + %d’, p(k), p(m));
                pairs = pairs + 1;
             end
          end
       end
      fprintf(‘. (%d pair’, pairs );
      if pairs > 1
         fprintf(‘s)\n’);
      else
         fprintf(‘)\n’);
      end
      n = input(‘>  ‘);
end
disp(‘Bye!’);

Solution 2.
disp(‘
Please enter a sequence of even numbers, each greater or equal to 4. ‘);
n = input(‘> ‘);
pairs = 0;
while mod( n, 2 ) == 0 & n >= 4
       fprintf(‘%d ‘, n );
      for ii = 1 : n/2
         if isprime( ii ) & isprime( n – ii )
            pairs = pairs + 1;
            fprintf(‘ = %d + %d’, ii, n - ii);
         end
      end
      fprintf(‘. (%d pair’, pairs );
      if pairs > 1
         fprintf(‘s)\n’);
      else
         fprintf(‘)\n’);
      end
      n = input(‘>  ‘);
end
disp(‘Bye!’);