本文介绍了使用C程序查找数字的最大素数因子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我写了一个代码,它以一个数字作为输入,并显示它的最大素数因子。该程序工作正常,直到9位数字。在9位数后,它表现出奇怪的负数。 #include< stdio.h> int largestprimefactor(unsigned long a) { int i = 2,largeprimefactor = 2; while(a!= 1) { if(a%i == 0) { while(a%i == 0 ) {a = a / i; printf(%d,i); if(i> largeprimefactor) { largeprimefactor = i; } } } i ++; } 返回largeprimefactor; } main() { unsigned long inputnumber; printf(输入数字:); scanf(%d,& inputnumber); printf(\ n%d的最大素数因子是%d,inputnumber,maximumprimefactor(inputnumber)); } 我的尝试: 我认为它可能是一个数据类型问题,所以我尝试使用unsigned long long但它没有帮助。解决方案 如果输入1 ,你的程序会说最大的素数因子是2.我怀疑是一个错误。 你还需要处理0和负数的结果。 您可以简化代码 而(a!= 1 ) { // 您可以删除测试,因为 while (a%i == 0 ) // 条件相同 {a = a / i; printf( %d,i); if (i> largeprimefactor) { largeprimefactor = i; } } i ++; } [更新] 你甚至可以简化更多。 while (a!= 1 ) { // 您可以删除测试,因为 while (a%i == 0 ) // 条件相同 {a = a / i; printf( %d,i); // 因为我永远不会低于largeprimefactor largeprimefactor = i; } i ++; } I wrote a code to which takes a number as input and displays the largest prime factor of it. The program is working fine till 9 digit numbers. After 9 digit numbers it is behaving weirdly showing negative numbers.#include<stdio.h> int largestprimefactor(unsigned long a){ int i =2 ,largeprimefactor = 2; while(a!=1) { if(a%i==0) { while(a%i==0) { a = a/i; printf("%d ",i); if(i>largeprimefactor) { largeprimefactor = i; } } } i++; } return largeprimefactor;} main(){ unsigned long inputnumber; printf("Enter a number : "); scanf("%d",&inputnumber); printf("\nThe largest prime factor of %d is %d",inputnumber,largestprimefactor(inputnumber));}What I have tried:I thought it might be a data type problem so I tried using unsigned long long but it doesn't help. 解决方案 If you input 1, your program will say that the largest prime factor is 2. I suspect an error.You also need to handle the result for 0 and negative numbers to be complete.You can simplify your codewhile(a!=1){ // you can remove the test because while(a%i==0) // the condition is the same { a = a/i; printf("%d ",i); if(i>largeprimefactor) { largeprimefactor = i; } } i++;}[Update]You can even simplify more.while(a!=1){ // you can remove the test because while(a%i==0) // the condition is the same { a = a/i; printf("%d ",i); // because i is never lower than largeprimefactor largeprimefactor = i; } i++;} 这篇关于使用C程序查找数字的最大素数因子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-14 07:35