文章

454

粉丝

0

获赞

1

访问

9.4k

头像
大整数的因子 题解(四语言 AC 代码)
P1182 北京大学上机题
发布于 2026年11月
阅读数 59

题意

给出不超过 30 位的十进制数 c,输出 2~9 中所有能整除它的 k;没有则输出 none。

思路

  • 大数取模:从高位逐位 (rem = rem*10 + digit) % k,即可判断 c % k 是否为 0。

  • 对 k=2..9 各算一次,按升序输出,空格分隔、末尾不留空格。

  • 输入可能含 -1 之类,遇到非法/负数直接跳过(题面提醒不要对 -1 计算)。

复杂度

时间 O(8·位数),空间 O(1)。

参考代码(C / C++ / Java / Python)

C:

#include <stdio.h>
#include <string.h>
int main(void){char s[64];
while(scanf("%s",s)==1){
int n=(int)strlen(s),i,k,found=0;
if(strcmp(s,"-1")==0)continue;
for(k=2;k<=9;k++){
int rem=0;
for(i=0;i<n;i++)rem=(rem*10+(s[i]-'0'))%k;
if(rem==0){
if(found)printf(" ");
printf("%d",k);found=1;
}}
if(!found)printf("none");
printf("\n");}
return 0;}

C++:

#include <iostream>
#include <string>
using namespace std;
int main(){string s;
while(cin>>s){
if(s=="-1")continue;
int n=(int)s.size();bool found=false;
for(int k=2;k<=9;k++){
int rem=0;
for(int i=0;i<n;i++)rem=(rem*10+(s[i]-'0'))%k;
if(rem==0){if(found)cout<<" ";cout<<k;found=true;}}
if(!found)cout<<"none";
cout<<"\n";}
return 0;}

Java:

import ...
登录查看完整内容


登录后发布评论

暂无评论,来抢沙发