Divisibility by 3 where each digit is the sum of all prefix digits modulo 10 | CPP code to check divisibility by 3 ; Function to check the divisibility ; Cycle ; no of residual terms ; sum of residual terms ; if no of residue term = 0 ; if no of residue term = 1 ; if no of residue term = 2 ; if no of residue term = 3 ; sum of all digits ; divisibility check ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string check ( long int k , int d0 , int d1 ) { long int s = ( 2 * ( d0 + d1 ) ) % 10 + ( 4 * ( d0 + d1 ) ) % 10 + ( 8 * ( d0 + d1 ) ) % 10 + ( 6 * ( d0 + d1 ) ) % 10 ; int a = ( k - 3 ) % 4 ; int x ; switch ( a ) { case 0 : x = 0 ; break ; case 1 : x = ( 2 * ( d0 + d1 ) ) % 10 ; break ; case 2 : x = ( 2 * ( d0 + d1 ) ) % 10 + ( 4 * ( d0 + d1 ) ) % 10 ; break ; case 3 : x = ( 2 * ( d0 + d1 ) ) % 10 + ( 4 * ( d0 + d1 ) ) % 10 + ( 8 * ( d0 + d1 ) ) % 10 ; break ; } long int sum = d0 + d1 + ( ( k - 3 ) / 4 ) * s + x ; if ( sum % 3 == 0 ) return " YES " ; return " NO " ; } int main ( ) { long int k , d0 , d1 ; k = 13 ; d0 = 8 ; d1 = 1 ; cout << check ( k , d0 , d1 ) << endl ; k = 5 ; d0 = 3 ; d1 = 4 ; cout << check ( k , d0 , d1 ) << endl ; return 0 ; }