1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
// Name: Connor McDowell
// Date: 1/30/3024
// class: CIS116
// Assignment: homework 3
#include <iostream>
#include "header.h"
using std::cin;
using std::cout;
using std::endl;
int main()
{
int f = 0;
int n = 0;
int m = 0;
int p = 0;
// factorial section
cout << "Enter a whole, positive number you would like to see go through a factorial calculation: ";
cin >> f;
cout << "The factorial of: " << f << " is: " << factorial(f) << endl;
// fib section
cout << "Please enter a whole, positive number to see the number located at your input's position in the fibonacci sequence: ";
cin >> n;
cout << "The number: " << fibonacci(n) << " is located at the position of input: " << n << endl;
// powerfunc section
cout << "Please enter a whole, positive number as the base for an exponential expression: ";
cin >> m;
cout << "And now a whole, positive number as the power to apply to the number: ";
cin >> p;
cout << m << " to the " << p << " power is: " << powerfunc(m, p);
return 0;
}
int factorial(int f)
{
// factorial equations with numbers as requested by the input cout statements will always be positive, and can get quite large.
// in this case, an unsigned number can be used as the sign of the number will always be positive and to prevent the memory from stacking up,
// using a size_t (unsigned long long) will prevent that, and in terms of efficiency, it is as fast as the int type.
if (f == 0 || f == 1)
return 1;
long calc = f * factorial(f - 1);
return calc;
}
int fibonacci(int n)
{
// for the same as above, though the int type is incredibly fast, the fibonacci sequence is all positive numbers, thus they dont need a sign
// and for above as well, the fibonacci sequence gets quite large incredibly quickly, and using a size_t will prevent hitting the number cap that
// int types have.
int a = 0, b = 1, c, i;
if (n == 0 || n == 1)
{
return n;
}
else
{
return(fibonacci(n - 1) + fibonacci(n - 2));
}
}
int powerfunc(int m, int p)
{
// though a sign can be useful in higher level applications for powers, in all actuality, a negative number only needs a sign on odd power values.
// for the even powers conversion to a size_t will reduce space and increase the number count.
if(p != 0)
{
return(m * powerfunc(m, p - 1));
}
else
{
return 1;
}
}
|