题解 | 大整数的因子(大整数取余一个小整数)

大整数的因子

https://www.nowcoder.com/practice/3d6cee12fbf54ea99bb165cbaba5823d

思路

30位超过long long 能够表示的范围,因此需要用通过string 实现大整数除法。

· 大整数除法思路

举个例子:123%3==0

大整数计算思路:

例子:123%3==0;
-------------------------------------------
res = 0;
[第一位:1]
	res = res*10+第一位 = 0*10+1 = 1;
	res = res%3 = 1;
[第二位:2]
	res = res*10+第二位 = 1*10+2 = 12;
	res = res%3 = 0;
[第三位:3]
	res = res*10+第三位 = 0*10+3 = 3;
	res = res%3 = 0;
-------------------------------------------
从高位到低位遍历结束 && res==0
  	说明此时的整数能被3整除

Code

#include <iostream>
#include <vector>
#include <limits>
using namespace std;

bool isDivisable(string num, int divider) {
    int total = 0;
    for(int i = 0; i<num.length(); i++) {
        int t = (num[i]-'0');
        total = total*10 + t;
        total %= divider;
    }
    if(total==0) return true;
    else return false;
}

int main() {
    string num;
    while (cin >> num) {
        if (num=="-1") break;
        vector<int> res;
        for (int i = 2; i<=9; i++) {
            if (isDivisable(num, i)) {
                res.push_back(i);
            }
        }
        if (res.empty()) {
            cout << "none" << endl;
        }
        for (auto it = res.begin(); it!=res.end();) {
            cout << (*it);
            if (++it == res.end()) cout << endl;
            else cout << " ";
        }
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

Lorn的意义:你这标个前端是想找全栈吗?而且项目确实没什么含金量,技术栈太少了,边沉淀边找吧 现在学院本想就业好一点四年至少得高三模式两年加油吧
点赞 评论 收藏
分享
酷酷我灵儿帅:这去不去和线不线下面说实话没啥关系
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-11 11:24
大家还是用ai改吧,我心疼得要死,就当花钱买教训吧,人家直接拿完钱就跑路了
程序员小白条:简历修改700....神奇,又不是帮你面试,咋的,简历修改从双非变92了还是没实习变成有大厂实习了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务