#include #include #include #include #include using namespace std; // checks if it is prime bool Prime(int num){ bool flag=true; if (num == 1) { return false; } for(int i = 2; i <= num / 2; i++) { if(num % i == 0) { flag = false; break; } } return flag; } int main() { ifstream input; string filename; cout << "Enter filename: "; cin >> filename; input.open(filename); vector> triang; string line; string num; //reading the file and stores in vector while(getline(input, line)) { istringstream nums(line); vector tmp; while(nums >> num) { tmp.push_back(stoi(num)); } triang.push_back(tmp); } /*for (int i = 0; i < triang.size(); i++) { for (int j = 0; j < triang[i].size(); j++) { cout << triang[i][j] << " "; } cout << endl; }*/ // with DP, starts to read triangle from bottom and goes to top. for (int i = triang.size()-2; i >= 0; i--) { for (int j = 0; j <= i; j++) { // for the bottom layer, just takes primes, compares each node's left and right child and sums if (i == triang.size()-2 && !Prime(triang[i][j])) { if (triang[i+1][j] >= triang[i+1][j+1] && !Prime(triang[i+1][j])) { triang[i][j] += triang[i+1][j]; } else if(!Prime(triang[i+1][j+1])) { triang[i][j] += triang[i+1][j+1]; } else { triang[i][j] = 0; } } // this is for other than bottom layer, I did not check primeness of children //because I already did in the bottom layer and now I am just adding else if (!Prime(triang[i][j])) { if (triang[i+1][j] >= triang[i+1][j+1]) { triang[i][j] += triang[i+1][j]; } else { triang[i][j] += triang[i+1][j+1]; } } else { triang[i][j] = 0; } } } // first element is the sum of maxPath cout << triang[0][0] << endl; return 0; }