function [ n,final ] = duration1 (p,s,r)
%duration1 This function computes the duration and final payment 
%for student loan or mortgage.

% consider negative value of payment, since loan is being paid off
s=-s;

%consider case that loan can be paid off
if r*p<-s
    
% compute n number of last month 
% before loan will be paid off fully
% (final payment will be made in the n-th month),
% the balance at the beginning of (n+1)-st month is zero
n=floor(-log(1+r*p/s)/log(1+r))+1; 

% compute final payment: take balance at beginning of n-th month
% and add interest to it (but not payment)!
% then final payment will be used to pay off exactly this sum
final=(1+r)*(p*(1+r)^(n-1)+s*((1+r)^(n-1)-1)/r);

% consider case that loan can never be paid off 
else 
    n=10000; % choose very large value for duration
    final=0; % assign value 0 to final payment 
end
end