Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

CSC112 Spring 2016 Examples

2370 views
1
/* create an arbitrary multiplication table.
2
*/
3
#include <iostream>
4
#include <iomanip>
5
#include <cmath>
6
#include "termmanip.h"
7
8
using namespace std;
9
10
bool isPrime(int n);
11
12
int main() {
13
int **table; //my table
14
int rows, cols; //rows and columns
15
int maxDigits;
16
int maxAnswer;
17
18
//get the number of rows and columnns
19
cout << "Rows: ";
20
cin >> rows;
21
cout << "Cols: ";
22
cin >> cols;
23
24
//compute the biggest
25
maxAnswer = rows * cols;
26
maxDigits = 1;
27
maxAnswer /= 10;
28
while(maxAnswer){
29
maxDigits++;
30
maxAnswer/=10;
31
}
32
33
34
//allocate the row pointers
35
table = new int*[rows];
36
37
//allocate the space for all the integers
38
table[0] = new int[rows * cols];
39
40
//organize pointers so our simple fleshy brains can handle it!
41
for(int i=1; i<rows; i++) {
42
table[i] = table[i-1] + cols;
43
}
44
45
//populate the table
46
for(int i=0; i<rows; i++) {
47
for(int j=0; j<cols; j++) {
48
table[i][j] = (i+1) * (j+1);
49
}
50
}
51
52
//print the header
53
cout << reverseVideo;
54
cout << setw(maxDigits) << ' ';
55
56
for(int col=1; col <= cols; col++) {
57
cout << setw(maxDigits+1) << col;
58
}
59
cout << ' ' << endl;
60
cout << normal;
61
62
//print the rows
63
for(int i=0; i<rows; i++) {
64
cout << reverseVideo;
65
cout << setw(maxDigits+1) << "+" << normal;
66
for(int j=0; j<cols; j++) {
67
cout << setfill('-') << setw(maxDigits+1) << '+';
68
}
69
cout << setfill(' ') << endl;
70
71
cout << reverseVideo;
72
cout << setw(maxDigits) << i+1 << "|";
73
cout << normal;
74
for(int j=0; j<cols; j++) {
75
if(isPrime(table[i][j])) {
76
cout << bold << magenta;
77
}
78
cout << setw(maxDigits) << table[i][j] << normal << "|";
79
}
80
cout << endl;
81
}
82
83
cout << reverseVideo << setw(maxDigits+1) << "+" << normal;
84
for(int j=0; j<cols; j++) {
85
cout << setfill('-') << setw(maxDigits+1) << '+';
86
}
87
cout << setfill(' ') << endl;
88
89
return 0;
90
}
91
92
93
//check primality
94
bool
95
isPrime(int n) {
96
int sn;
97
98
//handle evens
99
if(n%2 == 0) {
100
if(n == 2) {
101
return true;
102
} else {
103
return false;
104
}
105
}
106
107
if(n<=1) return false;
108
109
//check the others!
110
sn = (int) ceil(sqrt(n));
111
for(int factor=3; factor<=sn; factor+=2) {
112
if(n%factor == 0) return false;
113
}
114
115
//if we make it here, n is prime
116
return true;
117
}
118
119