DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

質數與尤拉函數

11.13.2008
| 753 views |
  • submit to reddit
        // description of your code here

#include <iostream>
#include <math.h>
using namespace std;


bool isPrime(int n)
{
	int i;
	for(i=2; i<=sqrt(n); i++)
	{
		if(((n % i) == 0))
		{
			return false;
		}
	}
	return true;
}

double Euler (int n)
{
	int a=3; //分子
	int b;   //分母	
	double pi = 2;
	int counter = 1;

	while(true)
	{
		if(isPrime(a) == true)
		{
			if(((a-1) % 4) != 0)
				b = a-1;
			else
				b = a+1;

			pi = pi*a/b;
			if(counter == n) 
				return pi;
			else
			{
				counter++;
				a++;
			}
		}else
			a++;
	}

}

void main()
{
	// 測試Euler函數
	cout<<Euler(10); 

	cout<<endl;
	system("pause");
}