tatya_bichu's blog

By tatya_bichu, history, 8 years ago, In English

Given T test cases T<=100000 In each test case given a positive integer A.A<=100000 You can perform any of the following steps(one of them):.

1) decrement A by 1.

2) increment A by 1.

3) divide A by one of it's prime factor.

Find minimum number of steps to reduce A to 1. 1) it is best to divide by max prime factor or finding nearest prime number whichever is minimum. This is codeforces problem but I can't find it

  • Vote: I like it
  • +4
  • Vote: I do not like it

| Write comment?
»
8 years ago, hide # |
 
Vote: I like it +4 Vote: I do not like it

Constraints of A?

»
8 years ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

if increment by 1 step would not be there then it can be done in aloga time..by maintaining the lowest prime divisor for each numbers(1->a) using seive then maintaining the answer(dynamic programming) array of size (a+1) using indices (1->a), ans[1]=0 and ans[i] can be calculated by min(ans[i-1],min(ans[i/p] for all prime divisors of i )) + 1. prime divisors for a particular number 'n' can be found in logn time hence it is (seive + aloga).. pls somebody explain how to do this with increment operation also

  • »
    »
    8 years ago, hide # ^ |
    Rev. 2  
    Vote: I like it 0 Vote: I do not like it

    Basically you can return 1 for each prime number and the prime gap at most can be around 100 so algo:

    Int solve(a){ If(a==1). Return 0;

    If(isprime[a]) return 1;

    Return min(solve (a-1),solve(a+1),solve(a/x)); // for all x which is prime divisor of a using seive).

    }

  • »
    »
    8 years ago, hide # ^ |
     
    Vote: I like it 0 Vote: I do not like it

    And use memoization

»
8 years ago, hide # |
Rev. 3  
Vote: I like it +27 Vote: I do not like it

This problem can be solved with Dijkstra. We extend the directed edge from x+1 to x and from x-1 to x. (1 <= x <= 100010) For the prime factor p of x, we extend the directed edge from x/p to x. You can use Dijkstra to find the distance from 1 to A_i. The solution is like this. The time complexity is

»
8 years ago, hide # |
 
Vote: I like it -9 Vote: I do not like it

build a graph and find the shortest path to reach from node A to node 1 using the Dijkstra algorithm.