## eamier 3 years ago i don't understand this in program to prime factorization.if(n%i==0) { n=n/i; 　　　　printf("%d,",i); i--; }

1. eamier

this is the full code: #include<stdio.h> main() { int n,i; printf("Enter a Number:"); scanf("%d",&n); printf("\n\nPrime Factors of %d is: ",n); for(i=2;i<=n;i++) { if(n%i==0) { n=n/i; printf("%d,",i); //n=n/i; i--; } } }

2. eamier

i don't know why need i--

3. tasreeb

decreasing the counter it is used for i--

4. eamier

i still don’t understand. what the counter for.

5. eamier

if i put like this: printf("%d,i); n=n/i; i--; it still correct, why we need n=n/i;i--;. we already get the value of i.

6. tasreeb

sorry i m not conformed about it but check ur code above u used the increment counter in for loop nd below the decreasing counter.

7. mihai995

the order of those instructions does not matter. It usually does, but not in this case. Also, I want to say that this program works poorly if it faces a large prime number. I recommend the following code: #include <stdio.h> int main(){ int n, i; scanf("%d", &n); printf("The prime factorization for %d is: ", n); for (i = 2 ; i * i <= n ; i++) while (n % i == 0){ n /= i; printf("%d ", i); } if (n != 1) printf("%d", n); return 0; }

8. eamier

if i skip [ n=n/i; i--; ] i will get all factor including not prime no. can you explain that part

9. eamier

and also this part n/ = i

10. mihai995

The reason you do [n /= i] is because you want to remove the factors of i in n. Let me give you an example: n = 42 When you iterate: i = 2: you divide n by 2 => n = 21 i = 3: you divide n by 3 => n = 7 This way, when you reach 6, you will not take it as a prime factor, because you already divided by 2 and 3. This way, 6 does not divide n anymore i hope you understand my explanations

11. eamier

so this mean that the sequence of dividing is 2,3,5,7,11...

12. eamier

skip number that already got its factor before

13. eamier

is it true?