This is a code I wrote in C to find if a given number is a Perfect number or Not.
A Perfect number is a number that is the sum of all its factors.
EXAMPLE - 6
6 has factors 2 , 3 and 1 (1 because it divisible by itself) and 2 3 1 = 6
#include <stdio.h>
int main(){
int number;
int sum =0,i;
scanf("%d",&number);
for(i=0;i<number;i ){
if(number % i==0){
sum = i;
}else{ sum = sum;}
}if(sum==number){
printf("Perfect Number");
}else{
printf("Not a Perfect Number");
}
return 0;
}
The code is logically correct and its suppose to give the right output but the problem is that it is not giving any output.
Instead in CLion it terminates with a code " Process finished with exit code -1073741676 (0xC0000094)"
CodePudding user response:
Your loop must have i
to start from 1
, not 0
, otherwise you'll have division by zero when you do number % i == 0
:
#include <stdio.h>
int main(void) {
int number;
int sum = 0;
printf("Insert number: ");
scanf("%d", &number);
// NOTE: replaced condition `i < number` with `i <= number / 2`
// for improved performance
for (int i = 1; i <= number / 2; i ) {
if (number % i == 0) {
sum = i;
}
}
if (sum == number) {
printf("Perfect Number\n");
}
else {
printf("Not a Perfect Number\n");
}
return 0;
}
CodePudding user response:
Here is a solution with Cyclomatic Complexity of 2. I don't see a reason for this, but you can do it.
#include <stdio.h>
int main(void)
{
int number = 33550336;
int sum = 0;
for(int i = 1; i <= number / 2; i ) {
sum = i * (number % i == 0);
}
printf("%d is %s", number, "not a perfect number." 4 * (sum==number));
return 0;
}