Advertisement
sirinehamza

P.I. Works

Jun 8th, 2020
1,236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.10 KB | None | 0 0
  1. #include <iostream>
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4.  
  5. bool isPrime(int n){
  6.     if(n==1||n==0){
  7.         return false;
  8.     }
  9.     for(int i=2;i<=(n/2);++i){
  10.         if(n%i==0){
  11.             return false;
  12.         }
  13.     }
  14.     return true;
  15. }
  16.  
  17. int maxPathSum(int tri[100][100],int row,int column,int totalRows,int *sum){
  18.     if(isPrime(tri[row][column])){
  19.         return 0;
  20.     }
  21.     if(row==totalRows-1){
  22.         *sum=tri[row][column];
  23.         return 1;
  24.     }
  25.     int sum_1=0,sum_2=0,state=0;
  26.     if(maxPathSum(tri,row+1,column,totalRows,&sum_1)){
  27.         state=1;
  28.     }
  29.     if(maxPathSum(tri,row+1,column+1,totalRows,&sum_2)){
  30.         state=1;
  31.     }
  32.     if(state){
  33.         if(sum_1>sum_2){
  34.             *sum=tri[row][column]+sum_1;
  35.             return 1;
  36.         }
  37.         else{
  38.             *sum=tri[row][column]+sum_2;
  39.             return 1;
  40.         }
  41.     }
  42.     else{
  43.         return 1;
  44.     }
  45. }
  46.  
  47. int getNumberOfLines(char filename[]){
  48.     string line;
  49.     int count=0;
  50.     ifstream file;
  51.     file.open(filename);
  52.     if(!file.is_open()){
  53.         return 0;
  54.     }
  55.     while(getline(file,line)){
  56.         count=count+1;
  57.     }
  58.     return count;
  59.     file.close();
  60. }
  61.  
  62. int main(void)
  63. {
  64.     char filename[100];
  65.     cout<<"Please enter the input file name :"<<endl;
  66.     cin>>filename;
  67.  
  68.     /*I assume maximum pyramid size is 100x100*/
  69.     int tri[100][100]={0};
  70.     int i;
  71.     int j;
  72.     ifstream file;
  73.     file.open(filename);
  74.     if(!file){
  75.         cout<<"Error! Cannot open input file! "<<endl;
  76.     }
  77.  
  78.     else{
  79.         for(i=0;i<getNumberOfLines(filename);i++){
  80.             for(j=0;j<=i;j++){
  81.                 file>>tri[i][j];
  82.             }
  83.         }
  84.  
  85.         /*To print the pyramid*/
  86.         /*for(i=0;i<getNumberOfLines(filename);i++){
  87.             for(j=0;j<=i;j++){
  88.                 cout<<tri[i][j]<<" ";
  89.             }
  90.             cout<<endl;
  91.         }*/
  92.  
  93.         int sum;
  94.         maxPathSum(tri,0,0,getNumberOfLines(filename),&sum);
  95.         cout<<"The maximum possible sum of the pyramid is "<<sum<<"."<<endl;
  96.  
  97.     }
  98.  
  99.     file.close();
  100.     return 0;
  101. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement