// Find perfect numbers. // derived from Variant 2: i is a factor of <=> a/i is a factor of a // g++ -Wno-deprecated PerfectNum3.cc #include #include #include // max ULL-int number: ULLONG_MAX main() { const unsigned long long int // interval to investigate iv1 = 1ULL, // 1 // iv1 = 8589869000, // max. number iv2 = 300000; // max. number // iv2 = 8589869100; // max. number // iv2 = ULONG_LONG_MAX; // max. number // iv2 = ULLONG_MAX; // undefined in g++ const unsigned long long int i_chk = iv2/1000;// check progress of work after i_chek loops unsigned long long int a, // number to investigate i,n, // loop index and last index sum_a; // sum of all factors cout << endl << " Start finding of perfect numbers " << endl << endl; for ( a=iv1; a<=iv2; a++ ) { if ( a%i_chk == 0) // Check the progress of the work { cout << "."; } // ----------- code from Var. 2 [start] ------------------------ n = floor(sqrt(a)); // NEW: last potential factor in Var.2 sum_a = 1; // NEW: Don't forget 1 for ( i=2; i<=n; i++ ) // NEW: we will start with 2 { if ( ( a % i ) == 0 ) // is var. i a factor? { sum_a += i + a/i; // NEW: add also a/i } } // ----------- code from Var. 2 [end] -------------------------- if ( sum_a == a) // output if var. a is a perfect number { cout << endl << " Perfect number: " << a << endl; } } cout << endl; } /* Perfect numbers are: 6 28 496 8128 33550336 // Laptop: user 0m0.002 / 0m0.004s fuer 4/8 Byte-int 8589869056 // Here, we need 8 Byte integers (long long int) // Laptop: user 0m0.013s [old: 7m25.344s] */