I'm to write a program that gives me the semiprimes up to some random number. I have the "formula" down but my loops skip the first couple semiprime values even though when tracing through it, I see no logical error.
#include <iostream>
using namespace std;
unsigned nthFactor(unsigned long UL, unsigned n);
unsigned numFactors( unsigned long UL);
bool isPrime ( unsigned long UL);
bool isPerfectSquare ( unsigned long UL);
bool isSemiPrime ( unsigned long UL);
int main()
{
unsigned long cnt=0;
unsigned long x;
for(x=1; x<100;x++)
{
if(isSemiPrime(x))
{
cout<<x<<endl;
cnt++;
}
}
cout<<"The number of semiprimes up to "<<x<<" is "<<cnt;
}
unsigned numFactors ( unsigned long UL) //this function takes whatever number u put into it and finds the amount of factors it has
{
unsigned cnt=0;
while ( nthFactor(UL,cnt++) !=0);
return cnt-1;
}
bool isSemiPrime ( unsigned long UL)
{
for(unsigned long x=2; x<=(UL/2); x++) //loops through all possible factors
{
if(UL%x==0 && numFactors(x)==1 ) //if x factors UL and x is a prime then...
{
if(numFactors(UL/x)==1) //if (UL/x) is also a prime then UL is a semiprime
return true;
}
}
return false;
}
Aucun commentaire:
Enregistrer un commentaire