I can't quit figure out how to print only perfect numbers. i.e. 6 factors out to 1, 2, 3. and 3+2+1=6, thus making a perfect number.
I have a program built that prints all numbers from 1 - UINT_MAX and I can't seem to print out only the perfect numbers...I also have one that uses a pointer and array, but im still not too sure on how to use pointers, they have been recently introduced and it only prints prime numbers.
Below code, prints all the primes, but no factors...
#include <limits.h>
#include <iostream>
usingnamespace std;
int main()
{
char buf[4096]; //where to store the numbers and than print only primes
char *cp; //char pointer
bool is_prime; //clearly a bool variable
unsigned num, i, sum; //unsigned max is around 4 billion
for (num = 1; num <= UINT_MAX; num++)
{
cp = buf;
is_prime = true;
cp += sprintf(cp ,"%u: ", num) ;//just naming the line with a number "num"
for(i = 2; i < num ; i++)
{
if(0 == (num % i))//if num evenly divides i, add it to print line
{
is_prime = false;
cp += sprintf(cp, "not prime\n");//writes everything that is prime
break;
cp += sprintf(cp, "%u ", i);//print the factors
}//close if
}//close for
cp += sprintf(cp, "\n");
if (is_prime)
printf("%s", buf);
}//close for
return 0;
}//main
Don't waste time calculating perfect numbers for every number.
Use the formula
possible_perfect = 2n-1(2n - 1)
to calculate all possible perfect numbers. Each time, check the possible_perfect number to see if it is, in fact, a perfect number.
I recommend you to the Wikipedia article on perfect numbers for that task: http://en.wikipedia.org/wiki/Perfect_number
Scroll down to the end of the section on even perfect numbers where it tells you how to calculate the digital root.
If the number is confirmed to be a perfect number, then print it. Otherwise continue with the next possibility.
**Update** So I am still trying to get the perfect numbers. I can't seem to do it, I'm trying to use a pointer "*cp" and a buffer "buf[1024]" and sprintf. I can't seem to figure out how to take numbers, store them in the array and than call them out once they meet the criteria of being a perfect number...
Why are you using sprintf() and char arrays[] ?
If you are trying to create a string of perfect numbers delimited by colons, for example
6:28:496:8128:
then use a stringstream for that purpose.
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
#include <sstream>
#include <string>
usingnamespace std;
int main()
{
stringstream result;
for (int i = 1; i <= 10; i++)
result << i << ":";
cout << result.str() << endl;
return 0;
}
BTW, n cannot be even. The formula 2n-1, where n is prime, produces numbers which include a class called Mersenne Primes. I'm pretty sure the Wikipedia article I linked for you mentions this.