DEV Community

Discussion on: Write a script to find "Perfect Numbers"

Collapse
 
rapidnerd profile image
George • Edited

Here's my solution in C

#include <stdio.h>

void  main(){
  int n, i, sum;
  int mn, mx;

  printf("Starting range: ");
  scanf("%d",&mn);

  printf("Ending range: ");
  scanf("%d",&mx);

  printf("Output: ");
  for(n = mn; n <= mx ; n++){
    i = 1;
    sum = 0;
    while(i < n){
      if(n % i == 0)
           sum = sum + i;
          i++;
    }
    if(sum== n)
      printf("%d ",n);
  }
      printf("\n");
}
Collapse
 
anduser96 profile image
Andrei Gatej

I think you can reduce the number of iterations by using “ while (i <=n/2)”.

Collapse
 
stefanrendevski profile image
Stefan Rendevski

You can reduce it even further by using "while (i <= sqrt(n))" and noticing that divisors come in pairs, for example: if 16 / 2 = 8, both 2 and 8 are divisors of 16. There is no need to go up to 8 and check all integers up until that point, you only need to perform the division.