결정론적 유한 자동화(DFA)는 숫자가 다른 숫자 k로 나눌 수 있는지 여부를 확인하는 데 사용됩니다. 나눌 수 없는 경우 이 알고리즘은 나머지도 찾습니다.
DFA 기반 디비전의 경우 먼저 DFA의 전환 테이블을 찾아야 하는데, 그 테이블을 사용하면 쉽게 답을 찾을 수 있습니다. DFA에서 각 상태에는 2개의 전환 0과 1만 있습니다.
입력 및 출력
Input: The number: 50 and the divisor 3 Output: 50 is not divisible by 3 and remainder is: 2
알고리즘
dfaDivision(num, k)
입력: 숫자 및 제수 k.
출력: 나눗셈과 나머지를 확인합니다.
Begin create transition table of size k * 2 //2 for transition 0 and 1 state = 0 checkState(num, state, table) return state End
checkState(숫자, 상태, 테이블)
입력: 숫자 번호, 상태 및 전환 테이블입니다.
출력: 나눗셈을 수행한 후 상태를 업데이트합니다.
Begin if num ≠ 0, then tempNum := right shift number for i bit checkState(tempNum, state, table) index := number AND 1 //perform logical and with number and 1 state := table[state][index] End
예
#include <iostream>
using namespace std;
void makeTransTable(int n, int transTable[][2]) {
int zeroTrans, oneTrans;
for (int state=0; state<n; ++state) {
zeroTrans = state<<1; //next state for bit 0
transTable[state][0] = (zeroTrans < n)? zeroTrans: zeroTrans-n;
oneTrans = (state<<1) + 1; //next state for bit 1
transTable[state][1] = (oneTrans < n)? oneTrans: oneTrans-n;
}
}
void checkState(int num, int &state, int Table[][2]) {
if (num != 0) { //shift number from right to left until 0
checkState(num>>1, state, Table);
state = Table[state][num&1];
}
}
int isDivisible (int num, int k) {
int table[k][2]; //create transition table
makeTransTable(k, table); //fill the table
int state = 0; //initially control in 0 state
checkState(num, state, table);
return state; //final and initial state must be same
}
int main() {
int num;
int k;
cout << "Enter Number, and Divisor: "; cin >> num>> k;
int rem = isDivisible (num, k);
if (rem == 0)
cout<<num<<" is divisible by "<<k;
else
cout<<num<<" is not divisible by "<<k<<" and remainder is: " << rem;
} 출력
Enter Number, and Divisor: 50 3 50 is not divisible by 3 and remainder is: 2