Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include<bits/stdc++.h>
- using namespace std;
- bool isPrime(int n){
- if(n==1||n==0){
- return false;
- }
- for(int i=2;i<=(n/2);++i){
- if(n%i==0){
- return false;
- }
- }
- return true;
- }
- int maxPathSum(int tri[100][100],int row,int column,int totalRows,int *sum){
- if(isPrime(tri[row][column])){
- return 0;
- }
- if(row==totalRows-1){
- *sum=tri[row][column];
- return 1;
- }
- int sum_1=0,sum_2=0,state=0;
- if(maxPathSum(tri,row+1,column,totalRows,&sum_1)){
- state=1;
- }
- if(maxPathSum(tri,row+1,column+1,totalRows,&sum_2)){
- state=1;
- }
- if(state){
- if(sum_1>sum_2){
- *sum=tri[row][column]+sum_1;
- return 1;
- }
- else{
- *sum=tri[row][column]+sum_2;
- return 1;
- }
- }
- else{
- return 1;
- }
- }
- int getNumberOfLines(char filename[]){
- string line;
- int count=0;
- ifstream file;
- file.open(filename);
- if(!file.is_open()){
- return 0;
- }
- while(getline(file,line)){
- count=count+1;
- }
- return count;
- file.close();
- }
- int main(void)
- {
- char filename[100];
- cout<<"Please enter the input file name :"<<endl;
- cin>>filename;
- /*I assume maximum pyramid size is 100x100*/
- int tri[100][100]={0};
- int i;
- int j;
- ifstream file;
- file.open(filename);
- if(!file){
- cout<<"Error! Cannot open input file! "<<endl;
- }
- else{
- for(i=0;i<getNumberOfLines(filename);i++){
- for(j=0;j<=i;j++){
- file>>tri[i][j];
- }
- }
- /*To print the pyramid*/
- /*for(i=0;i<getNumberOfLines(filename);i++){
- for(j=0;j<=i;j++){
- cout<<tri[i][j]<<" ";
- }
- cout<<endl;
- }*/
- int sum;
- maxPathSum(tri,0,0,getNumberOfLines(filename),&sum);
- cout<<"The maximum possible sum of the pyramid is "<<sum<<"."<<endl;
- }
- file.close();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement