c - Why did this prime factorisation algorithm give the correct answer even though there is a flaw? -


the problem stated me this:

"what largest prime factor of number 600851475143 ?"

the program used find answer using c:

#include<math.h> // remainder because % not work double or floats #include<stdio.h>   main() {     double x=600851475143,y=3.0;     while(x!=y)                         // divide until number can divide     {         if(remainder((x/y),1)==0.0)     // if x divisible y means factor magic         {             x=x/y;                      // divide number x y thereby reducing 1 constituent factor         }         y=y+2;                          // add 2 because odd numbers can prime , hence prime numbers can prime factors     }     printf("%lf",y);                    // printing magic } 

the question ask attempt check , divide x odd numbers, note not odd numbers not prime numbers, flaw in algorithm should cause answer wrong because in reality should checking prime factors (not odd factors).

surprisingly answer program spews out correct, checked answer.

how head around this? not make sense.

note there 3 flaws in algorithm:

  1. 2 prime number
  2. it might divide numbers not prime numbers , odd (like 9)
  3. it not divide prime number more once (as have expected numbers such 27).

from these can conclude broken algorithm yield correct answer if 2 following conditions apply:

  1. the input number odd (so skipping on 2 not matter)
  2. let number n = p1*p2*...*p_k p_i prime numbers. each j!=i : p_i != p_j. in here means each prime number factor of input number once, , problems 2+3 "avoided". (problem 2 - it's trivial why avoided, problem 3 avoided because divided number relevant prime factors, each m=p_i1*...*p_ic, since number divided prime factors - p_i1,...p_ic - fail divide m.

Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -