-5
printf("enter number:");
scanf("%d",&number);

for(i=2;i<number;i++){      
    if(number%i==0)
        printf("your number isn't prime\n");
    else 
        printf("your number is prime\n");
}

I wrote this code. The code runs but if I enter 10, it is printing many times that it isn't prime.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • Can you explain what "asal" means? And also, you're getting number from the user, but using it further on. Is that intentional? – fvu Jul 08 '18 at 22:01
  • Asal means is Prime number.I think the problem is there. I want to know if a number is a prime number, but it enters it more than once.how can I fixed this problem.I want to write one time your count is prime or not but this code writes more. – Carl Jackson Jul 08 '18 at 22:05
  • 1
    Once you know that the number is _not_ prime, `break` the loop. Only report that the number is prime _after_ the loop if `i==sayi`. – DYZ Jul 08 '18 at 22:11
  • it is working thanks for your help. – Carl Jackson Jul 08 '18 at 22:21
  • Sayi means is number. It is turkish word. – Carl Jackson Jul 08 '18 at 22:22
  • Have you tried running the program in your head? – user253751 Jul 09 '18 at 02:19
  • If you enter `10`, he loop will check `if (number%2 == 0)` and report it isn't prime, then check `if (number % 3 == 0)` and report it is prime, and so on, until it checks `if (number % 9 == 0)`. So the behaviour your describe is exactly what the code SHOULD give. If you want different behaviour, work out how to avoid printing out something on every loop iteration. – Peter Jul 09 '18 at 10:56

2 Answers2

1

Tip 1: try using a flag (but code would become longer,unnecessarily!) Tip 2: simply put a break statement after your first printf ;)

Rohit Sah
  • 27
  • 6
0

as mentioned in the comment by DyZ you should break the loop once you know that the number is not a prime and only report that the number is prime AFTER the loop.

Additionally you do not have to check multiples of already checked divisors. if your number is not divisible by 2 it is not divisible by any multiple of 2 like 4, 6, 8 and so on.

also, check following already answered question on prime numbers

R.S.
  • 276
  • 1
  • 8