Project Euler Homework

012.cpp

Go to the documentation of this file.
00001 
00017 #include <iostream>
00018 using namespace std;
00019 
00020 unsigned long
00021 factor (unsigned long S)
00022 {
00023   unsigned long no_of_factors = 1;
00024   unsigned power = 0;
00025 
00026   while (!(S &1)) //faster than S%2
00027     {
00028       S >>= 1; //faster than S/=2
00029       power++;
00030     }
00031   no_of_factors *= power + 1;
00032 
00033   power = 0;
00034   unsigned long last_factor = 3;
00035   for (unsigned long div = 3; S > 1 && S >= div;)
00036     {
00037       if (S % div != 0)         //skip if not divisible
00038         {
00039           div += 2;
00040           continue;
00041         }
00042       S /= div;
00043       if (div > last_factor)    //check divisibility of the same div again.
00044         {
00045           last_factor = div;
00046           no_of_factors *= power + 1;
00047           power = 1;
00048         }
00049       else
00050         power++;
00051     }
00052   //process the last factor
00053   if (S == 1)
00054     no_of_factors *= power + 1;
00055   return no_of_factors;
00056 }
00057 
00058 int
00059 main ()
00060 {
00061   unsigned long S = 1;
00062   for (int i = 1; factor (S) < 500; i++, S += i)
00063     {
00064     }
00065   cout << S << endl;
00066   return 0;
00067 }
00068 
 All Classes Files Functions Variables