Problems with a C program

Asked

Viewed 108 times

0

I’m having trouble developing a program that solves the problem below: Write a program that reads two integers M and N and calculate the average arithmetic of the prime numbers of the range [M, N].

First I decide to check if the program is working on its own, making the sum of the prime numbers in the interval. For example, in the range between 5 and 3, the result of the sum of prime numbers must be 8, but the sum is always going wrong. Someone could help me?

//EXERCICIO 107

#include<stdio.h>
#include<locale.h>
main(){
    setlocale(LC_ALL,"");
    int m,n,k,div,y,soma=0;
    printf("Informe dois números: ");
    scanf("%d%d",&m,&n);

    if(m > n){
        int cont=0;
        for(k=n;k<=m;k++){
            for(y=k;y>0;y--){
                div= k%y;
                if(div==0){
                    cont++;
                }
                if(cont==2){
                    soma = soma + k;
                }
            }
        }
        printf("A soma dos números primos entre o intervalo [%d,%d] é %d",m,n,soma);
        }

}

3 answers

2

I worked out the solution of the problem using part of his reasoning however, I implemented the code aiming to readability for a better understanding of the proposed algorithm, see:

#include <stdio.h>
#include <stdlib.h>

/* funcao capaz de verificar se um numero eh primo */
int eh_primo( unsigned long long n )
{
    unsigned long long i = 0;

    if(n <= 1)
        return 0;

    if( (n % 2) == (0 && n > 2) )
        return 0;

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

    return 1;
}


int main( void )
{
    unsigned long long k, m, n;
    unsigned long long soma = 0;
    unsigned long long contador = 0;
    long double media;

    printf("Informe dois numeros: ");
    scanf("%llu%llu",&m,&n);

    /* Verifica se o intervalo eh valido*/
    if( n > m )
    {
        /* percorre todos os numeros no intervalo */
        for( k = m; k <= n; k++ )
        {
            /* verifica se o numero atual eh um primo */
            if( eh_primo(k) )
            {
                /* faz o somatorio do numero primo encontrado */
                soma += k;

                /* incrementa contador de numeros primos */
                contador++;
            }
        }
    }

    /* se houver ao menos um numero primo no intervalo, calcula a media  */
    if( contador > 0 )
    {
        /* Calcula media aritmetica dos primos */
        media = soma / (long double) contador;

        /* exibe a media aritmetica na tela */
        printf("media = %Lg\n", media );
    }

    /* exibe contador de numeros primos no intervalo */
    printf("contador = %llu\n", contador );

    /* exibe o somatorio na tela */
    printf("somatorio = %llu\n", soma );

    return EXIT_SUCCESS;
}

See working on Ideone

0

You need to reset the variable counting each number of the range to be tested (at each value of k).

#include<stdio.h>
#include<locale.h>
main(){
    setlocale(LC_ALL,"");
    int m,n,k,div,y,soma=0;
    printf("Informe dois números: ");
    scanf("%d%d",&m,&n);

    if(m > n){
        for(k=n;k<=m;k++){
             int cont=0;
            for(y=k;y>0;y--){
                div= k%y;
                if(div==0){
                    cont++;
                }
            }
            if(cont==2){
                 soma = soma + k;
        }
        printf("A soma dos números primos entre o intervalo [%d,%d] é %d",m,n,soma);
    }

}

Another thing is that you can test if m>n and otherwise invert m and n and use the same code.

=================

Yes, the if(cont==2){ test was in the wrong place. Fixed.

  • I tested again by zeroing the counter the way you said, but the result is now 12. Any more suggestions than might be wrong?

0

Implementation without many strings, but with some comments and explanatory messages. Also with names of significant variables, instead of x, y, m, n, k, etc, and with comfortable eye spacing.

#include <stdio.h>
#include <stdlib.h>

// teste simples de primalidade
static int is_prime(int n)
{
  // menor que 2 nao e' primo
  if (n < 2)
    return 0;

  // 2 e' primo
  if (n == 2)
    return 1;

  // numero par nao e' primo
  if ((n & 1) == 0)
    return 0;

  // maior divisor de n possivel
  int meio_n = n / 2;

  for (int i = 3; i <= meio_n; i += 2)
    if ((n % i) == 0)
      return 0;

  return 1;
}

int main(void)
{
  int inf, sup, total = 0, n_primes = 0;

  printf("*\n");
  printf("* informe dois números: ");
  scanf("%d%d", &inf, &sup);
  printf("*\n");

  if (inf == sup)
  {
    if (is_prime(inf))
      printf("* %d e' primo, media e' o proprio %d\n", inf, inf);
    else
      printf("* %d nao e' primo, media e' 0\n", inf);
    printf("*\n");
    exit(0);
  }

  if (inf > sup)
  {
    int tmp = inf;
    inf = sup;
    sup = tmp;
  }

  for (int i = inf; i <= sup; i++)
    if (is_prime(i))
    {
      printf("* %d primo\n", i);
      total += i;
      n_primes++;
    }
    else
    {
      printf("* %d\n", i);
    }

  printf("*\n");

  if (n_primes > 0)
  {
    int avg = total / n_primes;
    printf("* existe(m) %d numero(s) primo(s) no intervalo [%d,%d]\n", n_primes, inf, sup);
    printf("* media dos numeros primos no intervalo [%d,%d] e' %d\n", inf, sup, avg);
  }
  else
  {
    printf("* nao existem numero primos no intervalo [%d,%d]\n", inf, sup);
  }

  printf("*\n");
}

Testing:

$./389893 
*
* informe dois números: 24 28
*
* 24
* 25
* 26
* 27
* 28
*
* nao existem numero primos no intervalo [24,28]
*

$./389893 
*
* informe dois números: 5 5
*
* 5 e' primo, media e' o proprio 5
*

$./389893 
*
* informe dois números: 6 6
*
* 6 nao e' primo, media e' 0
*

$./389893 
*
* informe dois números: 14 7
*
* 7 primo
* 8
* 9
* 10
* 11 primo
* 12
* 13 primo
* 14
*
* existe(m) 3 numero(s) primo(s) no intervalo [7,14]
* media dos numeros primos no intervalo [7,14] e' 10
*

$./389893 
*
* informe dois números: 7 14
*
* 7 primo
* 8
* 9
* 10
* 11 primo
* 12
* 13 primo
* 14
*
* existe(m) 3 numero(s) primo(s) no intervalo [7,14]
* media dos numeros primos no intervalo [7,14] e' 10
*

Browser other questions tagged

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