closed The following code doesn't show if a number is prime or not, where is the problem?

–2 votes
asked Jun 7, 2018 by KAUSTAV (720 points)
closed Jun 30, 2018 by KAUSTAV
#include <stdio.h>

int main()
{
    int n,i,sum =0;
    printf("Enter number = ");
    scanf("%d",&n);
    for(i=1;i<=n;i++)
    {
        if(n%i==0)
        {
            sum = sum + n + i;
        }
    }
    if(sum = 2*n+1)
    printf("Prime number");
    else printf("Not a prime number");
}
closed with the note: the answer by the below user is sufficient

1 Answer

0 votes
answered Jun 8, 2018 by Matheus Jahnke (440 points)
selected Jun 10, 2018 by KAUSTAV
 
Best answer
There is a "problem" in:
sum = 2*n+1(on the "if" just after the loop)
sum = 2*n+1 actually sets the value of sum to 2*n+1, and then evaluates if that is "true"(different from 0) or false(equals 0) .This is not "wrong" in the sense that it is actually valid code, however it is not intended behavior. To fix it you should put "==" instead of "=", because that will actually compare the numbers;
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...