Print a square where prime number positions receive a "#" and the others receive a "_"

Asked

Viewed 118 times

-1

#include <stdio.h>

int main () {

    int n, i, j;

    printf("Digite o tamanho do quadrado\n");

    scanf("%d", &n);

    for(i=1; i<=n; i++) {


        for(j=1; j<=n; j++) {

            if(i%j == 0) {

                printf("#");
            }

            else {
                printf("_");
            }

        }

        printf("\n");

    }


}
  • What... Is the doubt????

  • I can not print the positions that are prime number, is printing wrong, if you type 5 for example, will not print # in the positions 2, 3 , 5 and so respectively, the doubt is on how to print the positions that are prime number.

1 answer

0


#include <stdio.h>
#include <math.h>

int Primo(int n)
{
    if( n == 2 )
        return 1;

    if( !(n%2) || n == 1 )
        return 0;

    register int i;

    int maxP = (int)ceil(sqrt((double)n));

    for(i = 3; i <= maxP; i += 2)
        if( !(n % i) )
            return 0;

    return 1;
}

void DesenharQuadrado( int n )
{
    register int i, a;

    int count = 1;

    //Pergunta ficou ambigua, jeito 1 ou jeito 2?

    // // //Jeito 1
    // for(i = 0; i < n; i++)
    // {
        // for(a = 0; a < n; a++, count++)
            // if( Primo(count) )
                // printf("#");
            // else
                // printf("_");
        // printf("\n");
    // }

    // // // Jeito 2
    for(i = 0; i < n; i++)
    {
        for(a = 1; a <= n; a++)
            if( Primo(a) )
                printf("#");
            else
                printf("_");
        printf("\n");
    }
}

int main()
{
    int n;

    printf("Digite o tamanho do quadrado\n");   scanf("%d", &n);

    DesenharQuadrado(n);

    return (0);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.