检查函数:真素数问题

找出正整数 M 和 N 之间(N 不小于 M)的所有真素数。

真素数的定义:如果一个正整数 P 为素数,且其反序也为素数,那么 P 就为真素数。
例如,1113 均为真素数,因为11的反序还是为1113 的反序为 31 也为素数。

原题地址http://cxsjsx.openjudge.cn/practise2020pool/01A/

#include <iostream>
using namespace std;
//G VAR
const int G_MAX_SIZE = 100005;
bool G_NOT_PRIME[G_MAX_SIZE] = {
    
     false };//false 代表是素数



//FUNC
void getPrimesTable()
{
    
    
	G_NOT_PRIME[0] = G_NOT_PRIME[1] = true;

	for (int i = 2; i < G_MAX_SIZE; i++)
	{
    
    
		if (!G_NOT_PRIME[i])
		{
    
    
			for (int j = i + i; j < G_MAX_SIZE; j += i)
			{
    
    
				G_NOT_PRIME[j] = true;
			}
		}
	}
}

class Sol
{
    
    
public:
	Sol() {
    
    }
	Sol(int x, int y) : m_from(x), m_end(y)
	{
    
    
	}
	~Sol() {
    
    }

	

	void showAns()
	{
    
    
		bool isFirst = true;

		for (int i = m_from; i <= m_end; i++)
		{
    
    
			if (G_NOT_PRIME[i] == false)
			{
    
    
				int reverse_i = getReverse(i);
				if (G_NOT_PRIME[reverse_i] == false)
				{
    
    
					if (isFirst) cout << i;
					else
						cout << ',' << i;
					isFirst = false;
				}
			}
		}

		if (isFirst) cout << "No";
	}

	int getReverse(int x)
	{
    
    
		int ans = 0;
		while (x)
		{
    
    
			ans = ans * 10 + x % 10;
			x /= 10;
		}
		return ans;
	}

private:
	
	int m_from, m_end;
};



int main()
{
    
    
	int x, y;
	cin >> x >> y;
	Sol test(x, y);
	test.showAns();
	system("pause");
	return 0;
}

class Sol
{
    
    
public:
	Sol() {
    
    }
	Sol(int x, int y) : m_from(x), m_end(y)
	{
    
    
		A();
		//testA()
		D()
		//testD()
		C()
		//testC()
		B()
		//testB()
	}
	~Sol() {
    
    }

	void A(){
    
    }
	void B(){
    
    
		C();
	}
	void C(){
    
    
		D();
	}


private:

};

如上所示,先将底层的函数结果加以检查,正确后删除(或注释掉)

void showAns()
	{
    
    
		bool isFirst = true;

		for (int i = m_from; i <= m_end; i++)
		{
    
    
			if (m_isPrime[i] == false)
			{
    
    
				int reverse_i = getReverse(i);
				if (m_isPrime[reverse_i] == false)
				{
    
    
					if (isFirst) cout << i;
					else
						cout << ',' << i;
					isFirst = false;
				}
			}
		}

		if (isFirst) cout << "No" ;
	}

这里是经典的如何不输出最后的空格(或者其他的分割符),设立一个first标记第一个,第一个只输出自己,后边的则输出空格加数据。而且最后根据first的结果我们还可以知道是否有数据输出了。

猜你喜欢

转载自blog.csdn.net/qq_34890856/article/details/105868079