Friday, July 31, 2009

Please HELP, I have a logical error in C++!?

My Prof, requires that 1 isn't a prime number, my prog is returning 1 as a prime!


Please Help!





// Selection 3 Test a Number to see if it is Prime or Perfect!!!


else if (selection ==3)


{


while (ans=='y')


{


cout%26lt;%26lt;"Test a Number to See if it is Prime or Perfect"%26lt;%26lt;endl;


cout%26lt;%26lt;"Enter any Number Between 1 and 1000, Then Press 'Enter'"%26lt;%26lt;setw(2)%26lt;%26lt;":";


cin %26gt;%26gt;num;


cin.clear();


cin.ignore(100, '\n');


if (num%26gt;=1 %26amp;%26amp; num%26lt;=1000) //Validate input


{


cout%26lt;%26lt;"The Divisors for "%26lt;%26lt;num%26lt;%26lt;" are"%26lt;%26lt;endl;


squrt=sqrt(num);


for (divisor1=1,sum=0 ; divisor1%26lt;squrt ; divisor1++)//Formulate the output


{


if (num % divisor1==0)


{


divisor2=num/divisor1;


cout%26lt;%26lt;setw(58)%26lt;%26lt;divisor1%26lt;%26lt;" and "%26lt;%26lt;divisor2%26lt;%26lt;endl;


sum=sum+divisor1;


if (divisor1!=1)


{


sum=sum+divisor2;


}


}


}


if (divisor1==squrt)


{


cout%26lt;%26lt;setw(58)%26lt;%26lt;squrt%26lt;%26lt;endl;


sum=sum+squrt;


}


cout%26lt;%26lt;"The Number you Entered "%26lt;%26lt;num%26lt;%26lt;" is ";


if (sum ==1)


{


cout%26lt;%26lt;"a Prime Number"%26lt;%26lt;endl;


}


else if (sum==num)


{


cout%26lt;%26lt;"a Perfect Number"%26lt;%26lt;endl;


cout%26lt;%26lt;"the Sum of the Divisors is "%26lt;%26lt;sum%26lt;%26lt;endl;


}


else


{


cout%26lt;%26lt;"Not Prime or Prefect"%26lt;%26lt;endl;


cout%26lt;%26lt;"the Sum of the Divisors is "%26lt;%26lt;sum%26lt;%26lt;endl;


}


cout%26lt;%26lt;"If You Would Like to Test Another Number Press 'y', Otherwise Press Any Key"%26lt;%26lt;endl;


cin%26gt;%26gt;ans;


cin.clear();


cin.ignore(100, '\n');


}


else


{


cout%26lt;%26lt;"ERROR Invalid Number, Your Number MUST be Between 1 and 1000"%26lt;%26lt;endl;


}


}


}

Please HELP, I have a logical error in C++!?
If he doesn't want to see 1, then omit 1





I would include in your code comments that similar to this:





1 is mathematically a prime number,


but is being omitted per Professor Smith's instruction





As a programmer, I have included comments when I disagree with the requirements. as it serves as a bookmark for me or someone else should the end user requirements change.


No comments:

Post a Comment