printing of perfect numbers

Discussion in 'C' started by cindrilla, Apr 21, 2011.

  1. cindrilla

    cindrilla New Member

    Joined:
    Sep 26, 2010
    Messages:
    16
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    student
    Location:
    hyderabad
    hi friends i tried this logic to print the perfect numbers but there is no output at all pls can any one tell me wht's the mistake is?the code is as follows
    main()
    {
    int i,j,sum=0;
    for(i=1;i<=1000;i++)
    {
    for(j=1;j<i;j++)
    {
    if(i%j==0)
    sum=sum+j;
    }
    if(sum==i)
    printf("%d",i);
    }
    getch();
    }
     
  2. teacher

    teacher New Member

    Joined:
    Mar 27, 2011
    Messages:
    66
    Likes Received:
    8
    Trophy Points:
    0
    Occupation:
    i hate jobs
    Location:
    india,agra
    Home Page:
    http://www.crazylearner.in
    your logic is correct but you forget to reinitialize sum=0
    here is the correct code..
    Code:
    main()
    {
    int i,j,sum=0;
    for(i=1;i<=1000;i++)
    {
    for(j=1;j<i;j++)
    {
    if(i%j==0)
    sum=sum+j;
    }
    if(sum==i)
    printf("%d",i);
    sum=0; // insert this line in your code...
    }
    getch();
    } 
    
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice