gcd.cpp 求最大公因數
/* 輸入 {a,b} > 0 計算 a,b 的最大公因數 */
#include <iostream>
using namespace std;
int main()
{
int a,b;
while ( cin >> a >> b)
{
cout << a << "," << b << " 的 gcd ";
int c=a%b;
while( c )
{
a=b;
b=c;
c=a%b;
}
cout << b << endl;
}
return 0;
}
/*
執行範例
D:\cpp>gcd
100 55
100,55 的 gcd 5
1965 1155
1965,1155 的 gcd 15
^Z
*/
a的b次方÷1000取餘數
/* 輸入 1<{a,b}<1000 計算 a^b(a的b次方) 取最後三位數 */
#include <iostream>
using namespace std;
int main()
{
int a,b;
while( cin >> a >> b)
{
int p=1;
for(int i=1; i<=b; ++i)
{
p*=a; //乘 b 次
p %= 1000; // 每次皆除 1000 取餘數
}
cout << a << "^" << b << " 後3碼 = " << p << endl;
}
return 0;
}
/*
執行範例
D:\cpp>apb
123 456
123^456 後3碼 = 561
12 23
12^23 後3碼 = 128
987 654
987^654 後3碼 = 689
^Z
*/
2015年1月16日 星期五
P1 選修C 的三個Prime程式
除了以下這三個之外還有兩個範例,明日(1/17)會加入
第一個prime-1.cpp 輸入一個數 n 判斷是否為質數
#include <iostream>
using namespace std;
int main()
{
int n , i ;
while( cin >> n )
{
if(n==1) { cout << "No\n"; continue; }
for(i=2; i<n; ++i)
if( n % i == 0 ) break;
if( i <n ) cout << "No";
else cout << "Yes";
cout << endl;
}
system("pause");
return 0;
}
第二個prime-2.cpp 輸入一個數 n 判斷是否為質數
#include <iostream>
#include <cmath> // sqrt
using namespace std;
bool isp( int n ) // 函數方式判斷是否質數
{
int q = int(sqrt(n)); // 只須檢查至平方根
int i;
if(n==1) return false;
for(i=2; i<=q; ++i)
if( n % i == 0 ) return false;
return true;
}
int main()
{
int n ;
while( cin >> n )
{
if( isp(n) ) cout << "Yes\n";
else cout << "No\n";
}
system("pause");
return 0;
}
第三個prime-3.cpp 輸入一個數 n 列出1~n的質數,每10個換列
#include <iostream>
#include <cmath> // sqrt
using namespace std;
bool isp( int n )
{
int q = int(sqrt(n));
int i;
if(n==1) return false;
for(i=2; i<=q; ++i)
if( n % i == 0 ) return false;
return true;
}
int main()
{
int i,n,cnt ;
while( cin >> n )
{
cnt =0;
for(i=2; i<=n; ++i)
if( isp(i) )
{
cout << i << " ";
if((++cnt)%10==0) cout << endl;
}
cout << endl;
}
system("pause");
return 0;
}
第一個prime-1.cpp 輸入一個數 n 判斷是否為質數
#include <iostream>
using namespace std;
int main()
{
int n , i ;
while( cin >> n )
{
if(n==1) { cout << "No\n"; continue; }
for(i=2; i<n; ++i)
if( n % i == 0 ) break;
if( i <n ) cout << "No";
else cout << "Yes";
cout << endl;
}
system("pause");
return 0;
}
第二個prime-2.cpp 輸入一個數 n 判斷是否為質數
#include <iostream>
#include <cmath> // sqrt
using namespace std;
bool isp( int n ) // 函數方式判斷是否質數
{
int q = int(sqrt(n)); // 只須檢查至平方根
int i;
if(n==1) return false;
for(i=2; i<=q; ++i)
if( n % i == 0 ) return false;
return true;
}
int main()
{
int n ;
while( cin >> n )
{
if( isp(n) ) cout << "Yes\n";
else cout << "No\n";
}
system("pause");
return 0;
}
第三個prime-3.cpp 輸入一個數 n 列出1~n的質數,每10個換列
#include <iostream>
#include <cmath> // sqrt
using namespace std;
bool isp( int n )
{
int q = int(sqrt(n));
int i;
if(n==1) return false;
for(i=2; i<=q; ++i)
if( n % i == 0 ) return false;
return true;
}
int main()
{
int i,n,cnt ;
while( cin >> n )
{
cnt =0;
for(i=2; i<=n; ++i)
if( isp(i) )
{
cout << i << " ";
if((++cnt)%10==0) cout << endl;
}
cout << endl;
}
system("pause");
return 0;
}

