i am doing a question that asked to code a program to display FIRST 100 palindromic number.
i already have the function isPrime and isPalindrome.
but i dont know how to loop the first 100.
this is my main code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int main ()
{
for ( int i = 1; i <= 100; i++)
{
for(int j=1;j<=1000;j++)
{
if(isPrime(j) && isPalindrome(j))
{cout << setw(8) << j;}
}
}
cout << endl;
return 0;
}
You probably want something a little different to what you have. Your approach is looping up to fixed values. A better approach would be to loop until you get what you need.
I'll give you some pseudocode to give you a hint.
define integers for current number and number of palidromic primes
initialise both to zero
loop while the number of primes is less than 99 100
-- check to see if the current num is prime and palindrome
-- if it is, increment the number of primes variable and print out current number
-- increment current number before exiting loop
exit loop
int main ()
{
int j=0;
for ( int i = 0; i <= 100; i++)
{
while(j<99)
{
if(isPrime(j) && isPalindrome(j))
{cout << j;}
j++;
}
}
cout << endl;
return 0;
}
That's not going to work because you're incrementing j no matter what. That loop needs to end when you've found 100 primes, not after 100 iterations regardless.
You should only need one loop here; a while loop that loops until you've got your prime numbers. That while loop needs only one if statement inside of it.
Edited earlier response due to a mistake.
I'm a little reluctant to give out the code for this because it seems like it may be school/homework.