Can anyone tell me what is the problem here, considering I'm a beginner here? It is not showing Runtime error or something.
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int checkPrime(int n){
for (int i = 2; i * i < n; i ) {
if(n % i == 0 && i!=n)
return 0;
}
return n;
}
int main(){
int t;
scanf("%d",&t);
while(t--){
int n,sum=0;
scanf("%d",&n);
for(int i=n;i>1;i--){
if ( checkPrime(i) != 0 )
sum = i;
}
printf("%d\n",sum);
}
return 0;
}
CodePudding user response:
In checkPrime
, you have a loop
for(int i=0;i*i<n;i ){
if(n%i==0){
But in the first iteration, you have i=0
and then n%i
, but mod 0 is undefined behavior in C. I think what you want is
for (i = 2; i * i <= n; i )
UPDATE: In checkPrime
, you can eliminate count
entirely, as follows:
int checkPrime(int n) {
for (int i = 2; i * i <= n; i ) {
if(n % i == 0)
return 0;
}
return n;
}
This way, as soon as you find a divisor, you know the number isn't prime so you just return a 0. If you get all the way through the loop, then no divisor was found so the number is prime.
CodePudding user response:
OP's checkPrime()
has various troubles.
int checkPrime(int n){
for (int i = 2; i * i < n; i ) {
if(n % i == 0 && i!=n)
return 0;
}
return n;
}
Risks overflow
i * i
overflows when n
is a prime near INT_MAX
.
Returns non-zero (is a prime) for non-primes
checkPrime(1)
, checkPrime(negative values)
should return 0.
Useless code
i!=n
in if(n % i == 0 && i!=n)
is not needed.
Repaired
int checkPrime(int n){
for (int i = 2; i < n/i; i ) {
if (n % i == 0) {
return 0;
}
}
return n > 1;
}
Sum may overflow
//int n,sum=0;
...
//sum = i;
...
//printf("%d\n",sum);
int n;
long long sum=0;
...
sum = i;
...
printf("%lld\n", sum);
OP's overall code may have additional issues.