Guest User

Divby8

a guest
Oct 2nd, 2018
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.56 KB | None | 0 0
  1. // C++ program to find if there is a subsequence
  2. // of digits divisible by 8.
  3. #include <bits/stdc++.h>
  4. using namespace std;
  5.  
  6. // Function takes in an array of numbers,
  7. // dynamically goes on the location and
  8. // makes combination of numbers.
  9. bool isSubSeqDivisible(string str)
  10. {
  11.     int n = str.length();
  12.     int dp[n + 1][10];
  13.     memset(dp, 0, sizeof(dp));
  14.  
  15.     // Converting string to integer array for ease
  16.     // of computations (Indexing in arr[] is
  17.     // considered to be starting from 1)
  18.     int arr[n + 1];
  19.     for (int i = 1; i <= n; i++)
  20.         arr[i] = str[i - 1] - '0';
  21.  
  22.     for (int i = 1; i <= n; i++) {
  23.  
  24.         dp[i][arr[i] % 8] = 1;
  25.         for (int j = 0; j < 8; j++) {
  26.  
  27.             // If we consider the number in our combination,
  28.             // we add it to the previous combination
  29.             if (dp[i - 1][j] > dp[i][(j * 10 + arr[i]) % 8])
  30.                 dp[i][(j * 10 + arr[i]) % 8] = dp[i - 1][j];
  31.  
  32.             // If we exclude the number from our combination
  33.             if (dp[i - 1][j] > dp[i][j])
  34.                 dp[i][j] = dp[i - 1][j];
  35.         }
  36.     }
  37.  
  38.     for (int i = 1; i <= n; i++) {
  39.  
  40.         // If at dp[i][0], we find value 1/true, it shows
  41.         // that the number exists at the value of 'i'
  42.         if (dp[i][0] == 1)
  43.             return true;
  44.     }
  45.  
  46.     return false;
  47. }
  48.  
  49. // Driver function
  50. int main()
  51. {
  52.     string str = "3144";
  53.     if (isSubSeqDivisible(str))
  54.         cout << "Yes";
  55.     else
  56.         cout << "No";
  57.     return 0;
  58. }
Add Comment
Please, Sign In to add comment