PDA

View Full Version : Perfect and prime numbers


mrplow
18-11-2002, 05:04
This doesnt seem to work rite atm...



further down ;)

» Edited on 29-11-2002 by mrplow



pretty much complete c code listings lower down... just realised this is being linked to by a maths site :o

» Edited on 6-7-2003 by mrplow

mrplow
18-11-2002, 05:05
perfect numbers sure as hell dont come out right :S

dash
18-11-2002, 15:31
does now.... ;)

mrplow
18-11-2002, 20:37
It so nearly works properly... just doesn't output 2 in the list of primes...



// Program 1 : Perfect numbers


#include <stdio.h>
#include <math.h>


void main(void)
{
int isprime; // is it a prime or not? use this to store 0 or 1
int i; // counter
int j; // second counter
int theprimes[10000]; // have an array for the prime numbers, size 10000
int total=0; // keep track of number of items in array

int amount=10000; // used to allow fewer numbers in testing, set at 10000 for normal use

float k;
int perf,l,p; // for perfects

printf("nPrime numbers:n"); // heading for following data

for (i=1;i<=amount;i++) // go through possible primes ... don't start at zero
{
isprime=1;
if (i%2 != 0) // be sure number is not even (which cant possibly be a prime)..
{
// check for numbers that will divide into the prime with no remainder.. starting from 2, cause 1 will divide anything
// also, dont bother if we've already found a divisor for the prime

for (j=2;((j<(i/2)) && isprime);j++)

// dont bother with numbers greater than half of the prime.. cause there's no point tbh
{
if (i%j == 0) // if the possible prime divides into the possible divisor with no remainder, then it cant be a prime
isprime=0;

}

if (isprime == 1) // if we've found a prime lets record it into the array we set up
{
printf("%5i",i);
total++;
theprimes[total-1] = i; // into the array it goes
}
}
}


// we've found our primes, now for the perfects

printf("nPerfect numbers:n"); // heading for following data

for(i=2;i<=10000;i++) // set bounds
{
int s=1;
for(j=2;j<=i/2;j++)
if(i%j==0) s+=j;
if(s==i)
{
if(i<=amount)
printf("%5i is perfect.n", i); // output perfects within bounds
}
}


printf("nUsing formula:n"); // use formula as per question

for(i=0;i<=total;i++)
{
k = theprimes[ i]; l = pow(2,k)-1;
for(p=0;p<total;p++)
{
if( l == theprimes[p] )
{
perf = (pow(2,(k-1.0)))*((pow(2,k))-1.0); // here it is..
if(perf<=amount)
printf("Prime: %5i, Perfect: %5in",l,perf); // ..and here's
// the output
}
}
}

}



close enough for me ;)





» Edited on 29-11-2002 by mrplow

mrplow
29-11-2002, 13:00
hopefully that will be of some benefit to a lazy student somewhere ;)