Tuesday, October 31, 2017

650. 2 Keys Keyboard

https://leetcode.com/problems/2-keys-keyboard/description/
When n != 0, there the results is the sum of its prime factors.
    int minSteps(int n) {
        if(n == 1) return 0;
        int res = 0;
        vector<int> prime(n+1, 0);
        for(int i=2; i<prime.size(); i++) prime[i] = i;
        for(int i=2; i<prime.size(); i++) {
            int p = prime[i];
            if(p) {
                for(int j=2*p; j<prime.size(); j+=p) prime[j] = 0;
                while(n%p == 0) {
                   res += p;
                    n /= p;
                }
            }
        }
        return res;
    }

No comments:

Post a Comment