UVa 583

From Algorithmist
Jump to navigation Jump to search

583 - Prime Factors[edit]

Explanation[edit]

While a completely dumb approach to factoring a number is to try dividing by all possible factors in the range and checking their remainder, this will timeout. However, a slightly smarter approaching, trying all factors f in the range will run in time.

The reason checking the reduced set of candidates works is essentially that the smaller factor is never bigger than , a very short proof follows.

Consider a positive integer with positive factors and , so . Without loss of generality, choose to label the smaller number . So then , and , and therefore .

Gotcha's[edit]

Negative numbers are allowed, negate the input and remember the -1 coefficient before factoring.

Optimizations[edit]

These are not neccesary but will give you a faster time. The first optimization is simple, 2 is the only even prime, so after two, we can check only odd factors, which will reduce the possible factor space by a factor of 2, and give a nearly equal speed up.

An optimization that is a bit harder to implement is to pre-compute all the primes in the range with the Prime Sieve of Eratosthenes and use that as the candidate list.

There are only about ~5,000 primes from the time that it takes to generate all these primes are not as significant as making your program as optimized as possible on output.

  • Store the result in a string. (will save most of your time) output takes a long time.
  • While the number you are working with is not 1.

Input[edit]

-190
-191
-192
-193
-194
195
196
197
198
199
200
15152412
634637
12341
7
43
27724
0

Output[edit]

-190 = -1 x 2 x 5 x 19
-191 = -1 x 191
-192 = -1 x 2 x 2 x 2 x 2 x 2 x 2 x 3
-193 = -1 x 193
-194 = -1 x 2 x 97
195 = 3 x 5 x 13
196 = 2 x 2 x 7 x 7
197 = 197
198 = 2 x 3 x 3 x 11
199 = 199
200 = 2 x 2 x 2 x 5 x 5
15152412 = 2 x 2 x 3 x 11 x 191 x 601
634637 = 43 x 14759
12341 = 7 x 41 x 43
7 = 7
43 = 43
27724 = 2 x 2 x 29 x 239

Solutions[edit]