N=1e7; for n=2:N % A contains the unique prime factors of n; M their multiplicities [A,M]=factor(n); l=length(A); s=1; for i=1:l % formula for the sum of divisors of p^k c(i)=((A(i)^(M(i)+1))-1)/(A(i)-1); s*=c(i); end if 2*n==s printf("%d is Perfect!\n",n) m=n; k=0; while mod(m,2)==0 m=m/2; k++; end k++; printf("The corresponding Mersenne prime is %d\n",((2^k)-1)) end end