// Check weather a number is a perfect number // Variant 2: i is a factor of <=> a/i is a factor of a // code is much much faster // g++ -Wno-deprecated PerfectNum2.cc #include #include main() { long long int a, // number to investigate i,n, // loop index and last index sum_a; // sum of all factors cout << endl << " Input a = "; cin >> a; cout << endl; 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 } } cout << " a = " << a << " is "; if ( sum_a != a) // sum of factors not equal number a ? { cout << "not "; } cout << "a perfect number" << endl << 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] */