1

如果它不是素数,我希望这段代码能够打印一个数字的因子,如果它是素数,我希望它能够识别数字。

#include <stdio.h>

main() {
int possible_prime, n, possible_divisor;

printf( "\tThis program lists all primes <= n\n\n" );
printf( "Input n: " );
scanf( "%d", &n );
printf( "\n\n\tPrimes <= %d: \n\n", n );

    for ( possible_prime = 1; possible_prime <= n; possible_prime++ ) {
          /* try to find a divisor of possible_prime */

         for ( possible_divisor = 1; possible_divisor < possible_prime; possible_divisor++ ) {
             if ( possible_prime % possible_divisor == 0 )
                printf("\n\t%d", possible_prime);
               }

          /* found a divisor so possible_prime is not prime */
          break;

    if ( possible_divisor == possible_prime )
         /* exhausted possible divisors, so possible_prime is prime */
         printf( "%d\n", possible_prime );

   }
}

如果没有 if 语句下方的 printf,它可以正常工作。当我添加这个时,程序只打印“素数 <= n”,没有别的。我不明白为什么 printf 会搞砸循环?

4

2 回答 2

6

你的break陈述在错误的地方。将其放入内for循环;现在它for在检查 1 是否为素数后打破了外循环。

至于为什么只有在您添加了该内部print语句之后才会发生这种情况,我猜您最终在此过程中移动了一些花括号。

解决此问题后,您可能会发现您的程序告诉您没有什么是素数。您可能需要重新检查程序的素性条件。

于 2013-08-04T14:19:35.720 回答
1

您的程序既不会打印素数,也不会打印非素数的因子。这是您的代码的更正版本:

#include <stdio.h>

int main() 
{
    int possible_prime, n, possible_divisor;

    printf( "\tThis program lists all primes <= n\n\n" );
    printf( "\tInput n: " );
    scanf( "%d", &n );
    printf( "\n\n\tPrimes <= %d: \n\n", n );
    printf("Prime num\tNon-prime\n");
    printf("2\n");
    for ( possible_prime = 3; possible_prime <= n; possible_prime++ ) 
    {
            /* try to find a divisor of possible_prime */

            for ( possible_divisor = 2; possible_divisor < possible_prime; possible_divisor++) 
            {
                 if ( possible_prime % possible_divisor == 0 )
                 {
                     printf("\t\t%d:", possible_prime);
                     for (i = 1; i <= possible_prime; i++)
                     {
                         if(possible_prime % i == 0)
                            printf("%d ", i);
                     }
                 printf("\n");  
                 break;
                 }
            }

      /* found a divisor so possible_prime is not prime */


          if ( possible_divisor == possible_prime )
          /* exhausted possible divisors, so possible_prime is prime */
               printf( "%d\n", possible_prime );

    }
}
于 2013-08-04T14:56:31.543 回答