%------------------------------------------------------------------------ % % Matlab script to factor the integers from 1 to n, and then % count how many factors each integer has. This counts repetitions, % so 12 = 2*2*3 counts as three factors. Results are plotted. % % Features intended to be shown here: % % > how to format numbers when you don't know how many there are, % % > custom of saving all plots to image files and all of the % computed data to a Matlab binary file, % % > using the hist() function % %------------------------------------------------------------------------ % % Randall Bramley % Department of Computer Science % Indiana University, Bloomington % bramley somewhere around cs dot indiana dot (allegedly) edu % % Initiated : Mon 09 Mar 2009, 8:44 PM % Last Modified: Mon 09 Mar 2009, 12:46 PM to add these comments % %------------------------------------------------------------------------ n = 100000; f = zeros(n, 1); fid = fopen('factors', 'w'); for i = 1:n fI = factor(i); f(i) = length(fI); fprintf(fid, '%d:\t', i); %------------------------------------------------------------------- % Here is the trick for handling unknown number of values to print. % Matlab will cycle through the format specifier over and over until % it has printed all of the values in fI. %------------------------------------------------------------------- fprintf(fid, '%d\t', fI); fprintf(fid, '\n'); end fclose(fid); figure; plot(1:n, f, 'b+') title('Number of prime factors of integers 1:n') xlabel('Integer') ylabel('Number of Factors') print -dpng Factors.png s = unique(f); fn = length(s); nbars = max(10, fn); disp(sprintf('Maximum number of prime factors: %d', max(s))); disp(sprintf('Length of vector of unique numbers of prime factors: %d', fn)); figure; hist(f, nbars) title('Number of prime factors of integers 1:n') xlabel('Number of Factors') ylabel('Number of Integers with Given Number of Factors') print -dpng histygram.png save factor_info