#include #include #include using namespace std; bool isPrime(int num)//Function to check if an integer is prime or not { if (num <= 1) return false; for (int k = 2; k < int(sqrt(num)) + 1; k++) { if (num % k == 0) return false; } return true; } int maxSum(int** tree, int** tree_copy, int height) { if (isPrime(tree[0][0]))//If 0 0 is prime answer is zero return 0; for (int i = height - 1; i >= 0; i--) { for (int j = 0; j <= i; j++) { // function starts from bottom and works it way to top by addingmaximum number of tuples to the parent if (tree[i + 1][j] > tree[i + 1][j + 1]) tree[i][j] += tree[i + 1][j]; else tree[i][j] += tree[i + 1][j + 1]; } } return tree[0][0]; // top element = at the end equal to max sum } int main() { ifstream input; string filename, line; cout << "Please enter a filename for triangle data: ";//File input cin >> filename; input.open(filename.c_str()); while (input.fail()) { cout << "Cannot open the file." << endl; cout << "Please enter a filename for triangle data: "; cin >> filename; input.open(filename.c_str()); } int row = 0, col = 0; while (getline(input, line))//Get row count row++; col = (line.size() / 2) + 1; input.clear(); input.seekg(0); int** matrix = new int* [row];//Froming matrixes int** matrix_copy = new int* [row];//Form a copy to check for primes for (int i = 0; i < row; i++) { matrix[i] = new int[col]; matrix_copy[i] = new int[col]; for (int j = 0; j < col; j++)//Assign to 0 { matrix[i][j] = 0; matrix_copy[i][j] = 0; } } int k = 0; while (getline(input, line))//Read and transfer the file to matrix { istringstream ss(line); int num, j = 0; while (ss >> num) { if (isPrime(num) && !(k == 0 && j == 0)) num = INT_MIN; matrix[k][j] = num; matrix_copy[k][j] = num; j++; } k++; } cout << maxSum(matrix, matrix_copy, row - 1);//Print max sum for (int i = 0; i < row; i++)//Free the occupied memory from heap { delete[] matrix[i]; delete[] matrix_copy[i]; } delete[] matrix; delete[] matrix_copy; return 0; }