Professional Documents
Culture Documents
// Algorithms (p. 7)
#include <iostream>
using namespace std;
bool isPrime(int x)
{
for(int i = 2; i < x; i++)
{
if(x % i == 0)
return false;
}
return true;
}
// ============================================
// Algorithms (p. 10)
#include <iostream>
using namespace std;
void ruleOutPrime
(int x, bool isPrime[], int n);
int main()
{
int n = 0;
cin >> n; // must < 10000
bool isPrime[MAX_LEN] = {0};
for(int i = 0; i < n; i++)
isPrime[i] = true;
for(int i = 2; i <= n; i++)
{
if(isPrime[i] == true)
{
cout << i << " ";
ruleOutPrime(i, isPrime, n);
}
}
return 0;
}
void ruleOutPrime
(int x, bool isPrime[], int n)
{
for(int i = 1; x * i < n; i++)
isPrime[x * i] = false;
}
// ============================================
// Algorithms (p. 20)
int factorial(int n)
{
if(n == 1) // stopping condition
return 1;
else
// recursive call
return factorial(n - 1) * n;
}
// ============================================
// Algorithms (p. 22)
int fib(int n)
{
if(n == 1)
return 1;
else if(n == 2)
return 1;
else // two recursive calls
return (fib(n - 1) + fib(n - 2));
}
// ============================================
// Algorithms (p. 25)
double fibRepetitive(int n)
{
if(n == 1 || n == 2)
return 1;
int fib1 = 1, fib2 = 1;
int fib3 = 0;
for(int i = 2; i < n; i++)
{
fib3 = fib1 + fib2;
fib1 = fib2;
fib2 = fib3;
}
return fib3;
}
// ============================================
// Algorithms (p. 26)
int main()
{
int n = 0;
cin >> n;
cout << fibRepetitive(n) << "\n"; // algorithm 1
cout << fib(n) << "\n"; // algorithm 2
return 0;
}
// ============================================
// Algorithms (p. 29)
#include <iostream>
using namespace std;
hanoi(a, b, c, disc);
return 0;
}
void hanoi(char from, char via, char to, int disc)
{
if(disc == 1)
cout << "From " << from << " to " << to << "\n";
else
{
hanoi(from, to, via, disc - 1);
cout << "From " << from << " to " << to << "\n";
hanoi(via, from, to, disc - 1);
}
}