Euclid's
algorithm
#include
#include
int gcd (int a, int b)
{
int temp;
while (b != 0)
{
temp = a % b;
a = b;
b = temp;
}
return(a);
}
int main ()
{
int x, y;
cout << "Enter two natural numbers: ";
cin >> x >> y;
cout << "gcd(" << x << ", " << y << ") = " << gcd(x,y) << endl;
return(0);
}
Fibonacci numbers
#include
#include
int fib (int i)
{
int pred, result, temp;
pred = 1;
result = 0;
while (i > 0)
{
temp = pred + result;
result = pred;
pred = temp;
i = i-1;
}
return(result);
}
int main ()
{
int n;
cout << "Enter a natural number: ";
cin >> n;
while (n < 0)
{
cout << "Please re-enter: ";
cin >> n;
}
cout << "fib(" << n << ") = " << fib(n) << endl;
return(0);
}
Factorial
#include
#include
int fact (int i)
{
int result = 1;
while (i > 0)
{
result = result * i;
i = i-1;
}
return(result);
}
int main ()
{
int n;
cout << "Enter a natural number: ";
cin >> n;
while (n < 0)
{
cout << "Please re-enter: ";
cin >> n;
}
cout << n << "! = " << fact(n) << endl;
return(0);
}
No comments:
Post a Comment