The modulus is altering the value of primer
since when I print it before finding the modulus I get it's actual value but after finding modulus it turns to zero or one at times. It's a program that determines whether the number the user has entered is prime or not.
#include<stdio.h>
int main(){
int num;
int primer;
int mod;
printf("enter num> ");
scanf("%d", &num);
primer = num-1;
while(primer > 0){
mod = num%primer;
if(mod == 0){
printf("not prime");
break;}
if(primer == 1){
printf("prime");
break;}
primer--;}
}
CodePudding user response:
Beware of blaming language constructs (especially well-defined mathematical ones) for problems.
The problem is your code. It does not do what you think it does. You are trying to accomplish your task using two competing methods. Start over. Count from 2 and up when you are looping over possible divisors. Your variable name choices are not helping you either.
Remember, the computer will not help you solve this task. As a programmer, your job is to first solve the task yourself, and only second to tell the computer how to do it.
CodePudding user response:
Code fails with primes as it does primer == 1
and then mod == 0
is true - leading to "not prime".
mod = num%primer;
if (mod == 0) {
printf("not prime");
break;
}
// Too late
if (primer == 1) {
printf("prime");
break;
}
Code is inefficient as it makes O(num) tests.
Alternative, test with odd divisors: [3 ... square root of num
] - that is divisor*divisor <= num
.
divisor*divisor <= num
reformed as divisor <= num/divisor
to avoid overflow.
int isprime(int num) {
if (num % 2 == 0) {
return num == 2; // Only even prime
}
for (int divisor = 3; divisor <= num/divisor; divisor = 2) {
if (num%divisor == 0) {
return 0;
}
}
// Reach this point when num is a prime or an odd less than 3
return num >= 3;
}
CodePudding user response:
The problem isn't with the modulus at all seems like when primer
reaches one the result for num%primer
is 0 hence both conditions of the if statements are met seeing as to how mod == 0
and primer == 1
are both true
,a simple if(mod == 0 && primer != 1)
fixed it. As for the primer being one and zero at times that's also a classic case of my stupidity I was checking it's value within an if
statement hence the value was it's value after it was reduced by the loop.