- 3
Can someone help me to solve c language problem??
Create a function which receives a pointer of array as a parameter and calculates the sum of prime numbers and sum of non_prime numbers in that array. Then compares them to find out which one is larger (sum of prime or sum of non_prime). Return both sum of prime and sum of non_prime numbers also and print those in the main function.
1 Odpowiedź
+ 2
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#include <malloc.h>
int isPrime(int num)
{
for(int i=2;i*i<=num;i++)
if(num%2==0)
return 0;
return 1;
}
void sumPrimeAlso(int *ar,int size,int *sumPrime,int *sumNonPrime,int *comp)
{
for(int i=0;i<size;i++)
{
if(isPrime(ar[i]))
*sumPrime=*sumPrime+ar[i];
else
*sumNonPrime=*sumNonPrime+ar[i];
}
*comp=*sumPrime-*sumNonPrime;
}
int main(void) {
int n;
printf("Size of array:");
scanf("%i",&n);
int *ar=(int*)malloc(sizeof(int)*n);
for(int i=0;i<n;i++)
{
scanf("%i",&ar[i]);
}
int sumP=0;
int sumNonPrime=0;
int cmp;
sumPrimeAlso(ar,n,&sumP,&sumNonPrime,&cmp);
printf("Summ of prime numbers: %i\n",sumP);
printf("Summ of non prime numbers: %i\n",sumNonPrime);
if(cmp)
printf("sum of prime number higher than sum of non prime");
else
printf("sum of prime number less than sum of non prime"); free(ar); return 0; }