You are on page 1of 4

// ============================================

// Algorithms (p. 7)

#include <iostream>
using namespace std;

bool isPrime(int x);


int main()
{
int n = 0;
cin >> n;

for(int i = 2; i <= n; i++)


{
if(isPrime(i) == true)
cout << i << " ";
}
return 0;
}

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;

const int MAX_LEN = 10000;

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;

void hanoi(char from, char via, char to, int disc)


int main()
{
int disc = 0; // number of discs
cin >> disc;
char a = 'A', b = 'B', c = 'C';

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

You might also like