问题描述:
时间限制:
-
描述
- 已知正整数k满足2<=k<=9,现给出长度最大为30位的十进制非负整数c,求所有能整除c的k. 输入
-
若干个非负整数c,c的位数<=30
每行一个c,当c=-1时中止
(不要对-1进行计算!)
输出
-
每一个c的结果占一行
1) 若存在满足 c%k == 0 的k,输出所有这样的k,中间用空格隔开,最后一个k后面有空格。
2) 若没有这样的k则输出"none"
样例输入
-
30 72 13 -1
样例输出
-
2 3 5 6 2 3 4 6 8 9 none
提示
-
注意整数溢出问题
不要对-1进行计算
解题思路:
There is an Digit-Based approach to figure out if 7 is a factor of an integer:
Multiply each digit with 1 3 2 -1 -3 -2 recursively from the rightmost digit to the leftmost digit and add these multiplied digits together to form a new integer, if such integer is to be divided by 7, so is the original integer.
程序代码:
# include <iostream> # include <cstdio> # include <string> # include <vector> # include <cmath> # include <bitset> using namespace std; int checkList[6] = {1,3,2,-1,-3,-2}; bitset<8> affirm(0); int digitSum(vector<int>& a) { int len = a.size(); int total = 0; for ( int i = 0; i < len; i++ ) { total += a[i]; } return total; } void findFactor(string& str) { vector<int> inputNum; int len = str.length(); int sum = 0; int factor = 1; for ( int i = 0; i < len; i++ ) { inputNum.push_back(str[len-i-1]-'0'); } //Check 8,4,2 factor = 1; for ( int i = 0;( i < 3 && i < len ); i++ ) { sum += inputNum[i] * (int)pow(10,(double)i); } if ( sum % 2 == 0 ) { affirm[0] = true; } if ( sum % 4 == 0 ) { affirm[2] = true; } if ( sum % 8 == 0 ) { affirm[6] = true; } //Check 3,9 sum = digitSum(inputNum); if ( sum % 9 == 0 ) { affirm[7] = true; affirm[1] = true; } else if ( sum % 3 == 0 ) { affirm[1] = true; } //Check 5 if ( inputNum[0] == 0 || inputNum[0] == 5 ) { affirm[3] = true; } //Check 6 if ( affirm[0] == true && affirm[1] == true ) { affirm[4] = true; } //Check 7 - An Step-in approach sum = 0; for ( int i = 0; i < len; i++ ) { sum += checkList[i%6] * inputNum[i]; } if ( sum % 7 == 0 ) { affirm[5] = true; } } int main() { string input; int fact = 0; while ( cin >> input ) { if ( input == "-1" ) { break; } affirm.reset(); findFactor(input); if ( affirm.count() == 0 ) { cout << "none" << endl; } else { for ( int i = 0; i < 8; i++ ) { if ( affirm[i] == true ) { cout << i+2 << " "; } } cout << endl; } } return 0; }