Reputation: 1
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)"
Upvotes: 0
Views: 336
Reputation: 3428
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;
}
Function version:
#include <stdio.h>
#include <stdbool.h>
bool is_perfect(int number)
{
int sum = 0;
for(int i = 1; i <= number / 2; i++) {
sum += i * (number % i == 0);
}
return sum == number;
}
int main(void)
{
int n = 33550336;
printf("%d is %s", n, "not a perfect number." + 4 * is_perfect(n));
return 0;
}
The best version is this one with Cyclomatic Complexity of 1:
bool is_perfect(int n)
{
return n == 6 || n == 28 || n == 496 || n == 8128 || n == 33550336;
}
Much faster! 😅
Upvotes: 0
Reputation: 2892
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;
}
Upvotes: 1