Display first 100 palindromic prime numbers

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;
}


can anyone correct me please?
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


EDIT: No idea why I wrote 99 instead of 100.

Last edited on
How about this?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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.
Last edited on
Is this correct?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int main ()
{
	int count=1;
	int x;
	int collected=0;
	
	for(x=1;x<10000000;x++)
	{ if( isPrime(x) && isPalindrome(x))
	{ {cout << setw(8) << x;
	
	collected++;
	if(collected==100)
	{break;}
	}
	}
	}
	return 0;
}
Have you tested it? Does it produce 100 palindromic primes?
you don't have to make the loop end at a number

you can do something like
1
2
3
4
5
6
7
8
9
10
11
int number=0;
int counter=0;
while(counter<100)
{
    if (number is palin and prime)
    {
        print
        counter++;
    }
    number++
}
Last edited on
Yes it is correct thank you =)
Topic archived. No new replies allowed.