Trudne pytanie o wywiad Google

Mój przyjaciel szuka pracy. Jedno z pytań z wywiadu dało mi do myślenia, chciałem tylko trochę informacji zwrotnej.

Istnieją 2 nieujemne liczby całkowite: i I j. biorąc pod uwagę następujące równanie, znajdź (optymalne) rozwiązanie, aby iterację nad i I j w taki sposób, że wyjście jest sortowane.

2^i * 5^j

Więc kilka pierwszych rund wyglądałoby tak:

2^0 * 5^0 = 1
2^1 * 5^0 = 2
2^2 * 5^0 = 4
2^0 * 5^1 = 5
2^3 * 5^0 = 8
2^1 * 5^1 = 10
2^4 * 5^0 = 16
2^2 * 5^1 = 20
2^0 * 5^2 = 25
Nie widzę wzoru. Twoje myśli?
Author: Will Ness, 2011-04-01

21 answers

Dijkstra wywodzi wymowne rozwiązanie w "dyscyplinie programowania". Przypisuje problem Hammingowi. Oto moja implementacja rozwiązania Dijkstry.

int main()
{
    const int n = 20;       // Generate the first n numbers

    std::vector<int> v(n);
    v[0] = 1;

    int i2 = 0;             // Index for 2
    int i5 = 0;             // Index for 5

    int x2 = 2 * v[i2];     // Next two candidates
    int x5 = 5 * v[i5];

    for (int i = 1; i != n; ++i)
    {
        int m = std::min(x2, x5);
        std::cout << m << " ";
        v[i] = m;

        if (x2 == m)
        {
            ++i2;
            x2 = 2 * v[i2];
        }
        if (x5 == m)
        {
            ++i5;
            x5 = 5 * v[i5];
        }
    }

    std::cout << std::endl;
    return 0;
}
 116
Author: user515430,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-19 18:58:35

Oto bardziej wyrafinowany sposób na zrobienie tego (bardziej wyrafinowany niż moja poprzednia odpowiedź, czyli):

Wyobraź sobie, że liczby są umieszczone w macierzy:

     0    1    2    3    4    5   -- this is i
----------------------------------------------
0|   1    2    4    8   16   32
1|   5   10   20   40   80  160
2|  25   50  100  200  400  800
3| 125  250  500 1000 2000 ...
4| 625 1250 2500 5000 ...
j on the vertical

To, co musisz zrobić, to "przejść" tę matrycę, zaczynając od (0,0). Musisz również śledzić, jakie są Twoje możliwe następne ruchy. Gdy zaczynasz od (0,0), Masz tylko dwie opcje: (0,1) lub (1,0): ponieważ wartość (0,1) jest mniejsza, wybierasz ją. następnie zrób to samo dla następnego wyboru (0,2) lub (1,0). Jak dotąd, ty mieć następującą listę: 1, 2, 4. Twój następny ruch to (1,0), ponieważ tam wartość jest mniejsza niż (0,3). Jednak teraz masz trzy wybory do następnego ruchu: albo (0,3), albo (1,1), albo (2,0).

Nie potrzebujesz matrycy, aby uzyskać listę, ale musisz śledzić wszystkie swoje wybory (tzn. gdy dojdziesz do 125+, będziesz miał 4 wybory).

 47
Author: vlad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-03-31 21:00:41

Użyj sterty Min.

Put 1.

Ekstrakt-Min. Say you get x.

Wcisnąć 2x i 5x w stertę.

Powtórz.

Zamiast przechowywać x = 2^i * 5^j, możesz przechowywać (i, j)i używać niestandardowej funkcji porównywania.

 23
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-03-31 20:30:06

Rozwiązanie oparte na FIFO wymaga mniejszej pojemności. Kod Pythona.

F = [[1, 0, 0]]             # FIFO [value, i, j]
i2 = -1; n2 = n5 = None     # indices, nexts
for i in range(1000):       # print the first 1000
    last = F[-1][:]
    print "%3d. %21d = 2^%d * 5^%d" % tuple([i] + last)
    if n2 <= last: i2 += 1; n2 = F[i2][:]; n2[0] *= 2; n2[1] += 1
    if n5 <= last: i2 -= 1; n5 = F.pop(0); n5[0] *= 5; n5[2] += 1
    F.append(min(n2, n5))

Wyjście:

  0.                     1 = 2^0 * 5^0
  1.                     2 = 2^1 * 5^0
  2.                     4 = 2^2 * 5^0
 ...
998. 100000000000000000000 = 2^20 * 5^20
999. 102400000000000000000 = 2^27 * 5^17
 13
Author: GaBorgulya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-04-01 02:17:18

Jest to bardzo łatwe do zrobienia O(n) w językach funkcyjnych. Lista l z 2^i*5^j liczb może być po prostu zdefiniowana jako 1, a następnie 2*l i 5*l połączone. Oto Jak to wygląda w Haskell:

merge :: [Integer] -> [Integer] -> [Integer]
merge (a:as) (b:bs)   
  | a < b   = a : (merge as (b:bs))
  | a == b  = a : (merge as bs)
  | b > a   = b : (merge (a:as) bs)

xs :: [Integer]
xs = 1 : merge (map(2*)xs) (map(5*)xs)

Funkcja merge daje nową wartość w stałym czasie. Tak jak map i dlatego tak jest l.

 6
Author: Thomas Ahle,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-16 15:55:58

Musisz śledzić poszczególne wykładniki z nich i jakie byłyby ich sumy

Więc zaczynasz od f(0,0) --> 1 teraz musisz zwiększyć jeden z nich:

f(1,0) = 2
f(0,1) = 5

Więc wiemy, że 2 jest następnym-wiemy również, że możemy zwiększyć wykładnik i aż suma przekroczy 5.

/ Align = "left" /
 5
Author: corsiKa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-03-31 20:45:51

Używając dynamicznego programowania możesz to zrobić w O (n). Prawda jest taka, że żadne wartości i I j nie mogą dać nam 0, a aby otrzymać 1, obie wartości muszą być 0;

TwoCount[1] = 0
FiveCount[1] = 0

// function returns two values i, and j
FindIJ(x) {
    if (TwoCount[x / 2]) {
        i = TwoCount[x / 2] + 1
        j = FiveCount[x / 2]
    }
    else if (FiveCount[x / 5]) {
        i = TwoCount[x / 2]
        j = FiveCount[x / 5] + 1
    }
}

Gdy wywołujesz tę funkcję Sprawdź, czy i I j są ustawione, jeśli nie są null, To wypełnij TwoCount i FiveCount


C++ odpowiedz Przepraszam za zły styl kodowania, ale spieszę się: (

#include <cstdlib>
#include <iostream>
#include <vector>

int * TwoCount;
int * FiveCount;

using namespace std;

void FindIJ(int x, int &i, int &j) {
        if (x % 2 == 0 && TwoCount[x / 2] > -1) {
                cout << "There's a solution for " << (x/2) << endl;
                i = TwoCount[x / 2] + 1;
                j = FiveCount[x / 2];
        } else if (x % 5 == 0 && TwoCount[x / 5] > -1) {
                cout << "There's a solution for " << (x/5) << endl;
                i = TwoCount[x / 5];
                j = FiveCount[x / 5] + 1;
        }    
}

int main() {
        TwoCount = new int[200];
        FiveCount = new int[200];

        for (int i = 0; i < 200; ++i) {
                TwoCount[i] = -1;
                FiveCount[i] = -1;
        }

        TwoCount[1] = 0;
        FiveCount[1] = 0;

        for (int output = 2; output < 100; output++) {
                int i = -1;
                int j = -1;
                FindIJ(output, i, j);
                if (i > -1 && j > -1) {
                        cout << "2^" << i << " * " << "5^" 
                                     << j << " = " << output << endl;
                        TwoCount[output] = i;
                        FiveCount[output] = j;
                }
        }    
}

Oczywiście możesz użyć struktur danych innych niż tablica, aby dynamicznie zwiększyć swoją pamięć itp. To tylko szkic do udowodnij, że to działa.

 4
Author: Mikhail,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-05 17:39:24

Dlaczego nie spojrzeć na to z innej strony? Użyj licznika, aby przetestować możliwe odpowiedzi na podstawie oryginalnej formuły. Przepraszam za pseudo kod.

for x = 1 to n
{
  i=j=0
  y=x
  while ( y > 1 )
  {
    z=y
    if y divisible by 2 then increment i and divide y by 2
    if y divisible by 5 then increment j and divide y by 5

    if y=1 then print i,j & x  // done calculating for this x

    if z=y then exit while loop  // didn't divide anything this loop and this x is no good 
  }
}
 2
Author: Lost in Alabama,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-03-31 21:12:12

Niniejszy jest odpowiednim wpisem w OEIS.

Wydaje się, że możliwe jest uzyskanie uporządkowanej sekwencji poprzez wygenerowanie pierwszych kilku terminów, powiedzmy

1 2 4 5

A następnie, zaczynając od drugiego terminu, mnożąc przez 4 i 5, aby uzyskać następne dwa

1 2 4 5 8 10

1 2 4 5 8 10 16 20

1 2 4 5 8 10 16 20 25

I tak on..

Intuicyjnie wydaje się to słuszne, ale oczywiście brakuje dowodu.

 2
Author: abeln,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-03-31 21:26:49

Wiesz, że log_2(5)=2,32. Z tego możemy zauważyć, że 2^2 5.

Teraz spójrz na macierz możliwych odpowiedzi:

j/i  0   1   2   3   4   5
 0   1   2   4   8  16  32
 1   5  10  20  40  80 160 
 2  25  50 100 200 400 800
 3 125 250 500 ...

Teraz, w tym przykładzie, wybierz liczby w kolejności. Byłoby:

j/i  0   1   2   3   4   5
 0   1   2   3   5   7  10
 1   4   6   8  11  14  18
 2   9  12  15  19  23  27
 3  16  20  24...

Zauważ, że każdy wiersz rozpoczyna się 2 kolumnami za wierszem rozpoczynającym go. Na przykład i=0 j=1 pojawia się bezpośrednio po i=2 j=0.

Algorytm, który możemy wyprowadzić z tego wzoru jest zatem (Załóżmy j > i):

int i = 2;
int j = 5;
int k;
int m;

int space = (int)(log((float)j)/log((float)i));
for(k = 0; k < space*10; k++)
{
    for(m = 0; m < 10; m++)
    {
        int newi = k-space*m;
        if(newi < 0)
            break;
        else if(newi > 10)
            continue;
        int result = pow((float)i,newi) * pow((float)j,m);
        printf("%d^%d * %d^%d = %d\n", i, newi, j, m, result);
    }
}   

Uwaga: kod tutaj oznacza wartości wykładników i I j są mniejsze niż 10. Możesz łatwo rozszerzyć ten algorytm, aby pasował do innych arbitralnych granic.

Uwaga: czas działania tego algorytmu wynosi O (n) dla pierwszych n odpowiedzi.

Uwaga: złożoność przestrzeni dla tego algorytmu wynosi O (1)

 1
Author: KLee1,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-03-31 23:47:33

Moja realizacja opiera się na następujących pomysłach:

  • Użyj dwóch kolejek Q2 i Q5, obie zainicjowane przez 1. Będziemy trzymać obie kolejki w uporządkowanej kolejności.
  • na każdym kroku Usuń najmniejszy element liczby MIN z Q2 lub Q5 i wydrukuj go. Jeśli zarówno Q2, jak i Q5 mają ten sam element - Usuń oba. Wydrukuj ten numer. Jest to w zasadzie Scalanie dwóch posortowanych tablic - na każdym kroku wybierz najmniejszy element i postępuj.
  • Enqueue MIN * 2 do Q2 i MIN * 5 do Q5. Ta zmiana nie łamie niezmiennika sortowanego Q2/Q5, ponieważ MIN jest wyższa niż poprzednia liczba MIN.

Przykład:

Start with 1 and 1 (to handle i=0;j=0 case):
  Q2: 1
  Q5: 1
Dequeue 1, print it and enqueue 1*2 and 1*5:
  Q2: 2
  Q5: 5
Pick 2 and add 2*2 and 2*5:
  Q2: 4
  Q5: 5 10
Pick 4 and add 4*2 and 4*5:
  Q2: 8
  Q5: 5 10 20
....

Kod w Javie:

public void printNumbers(int n) {
    Queue<Integer> q2 = new LinkedList<Integer>();
    Queue<Integer> q5 = new LinkedList<Integer>();
    q2.add(1);
    q5.add(1);
    for (int i = 0; i < n; i++) {
        int a = q2.peek();
        int b = q5.peek();
        int min = Math.min(a, b);
        System.out.println(min);
        if (min == a) {
            q2.remove();
        }
        if (min == b) {
            q5.remove();
        }
        q2.add(min * 2);
        q5.add(min * 5);
    }
}
 1
Author: ejboy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-12 18:15:36

Oblicz wyniki i umieść je na posortowanej liście, wraz z wartościami dla i i j

 0
Author: vlad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-03-31 20:32:42

Algorytm zaimplementowany przez user515430 przez Edsgera Dijkstra (http://www.cs.utexas.edu/users/EWD/ewd07xx/EWD792.PDF) jest prawdopodobnie tak szybki, jak można dostać. Każdy numer, który jest formą 2^i * 5^j, nazywam "numerem specjalnym". Teraz odpowiedź będzie O(i*j), ale z podwójnym algorytmem, jeden do generowania liczb specjalnych O(i*j) i jeden do ich sortowania (zgodnie z linkowanym artykułem również O(i*j).

Ale sprawdźmy algorytm Dijkstry(patrz niżej). W tym przypadku n jest ilością specjalnych liczby, które generujemy, więc równe i*j. Zapętlamy się raz, 1 -> n i w każdej pętli wykonujemy stałą akcję. Więc algorytm ten jest również O(i*j). I z całkiem płonącą, szybką stałą.

Moja implementacja w C++ z GMP( C++ wrapper), i zależy od boost::lexical_cast, choć to można łatwo usunąć (jestem leniwy, a kto nie używa Boost?). Skompilowane z g++ -O3 test.cpp -lgmpxx -o test. Na Q6600 Ubuntu 10.10 time ./test 1000000 daje 1145ms.

#include <iostream>
#include <boost/lexical_cast.hpp>
#include <gmpxx.h>

int main(int argc, char *argv[]) {
    mpz_class m, x2, x5, *array, r;
    long n, i, i2, i5;

    if (argc < 2) return 1;

    n = boost::lexical_cast<long>(argv[1]);

    array = new mpz_class[n];
    array[0] = 1;

    x2 = 2;
    x5 = 5;
    i2 = i5 = 0;

    for (i = 1; i != n; ++i) {
        m = std::min(x2, x5);

        array[i] = m;

        if (x2 == m) {
            ++i2;
            x2 = 2 * array[i2];
        }

        if (x5 == m) {
            ++i5;
            x5 = 5 * array[i5];
        }
    }

    delete [] array;
    std::cout << m << std::endl;

    return 0;
}
 0
Author: orlp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-03-31 23:15:15

Jeśli narysujesz macierz z i jako wierszem i j jako kolumną, zobaczysz wzór. Zacznij od i = 0, a następnie po prostu przemierzaj matrycę, przechodząc w górę 2 wiersze i w prawo 1 kolumnę, aż dotrzesz do góry matrycy (j >= 0). Następnie przejdź i + 1, itp...

Więc dla i = 7 podróżujesz tak:

7, 0 -> 5, 1 -> 3, 2 -> 1, 3

I dla i = 8:

8, 0 -> 6, 1 -> 4, 2 -> 2, 3 -> 0, 4

Tutaj to jest w Javie idąc do i = 9. Wyświetla pozycję macierzy (i, j) i wartość.

for(int k = 0; k < 10; k++) {

    int j = 0;

    for(int i = k; i >= 0; i -= 2) {

        int value = (int)(Math.pow(2, i) * Math.pow(5, j));
        System.out.println(i + ", " + j + " -> " + value);
        j++;
    }
}
 0
Author: Cubby,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-04-01 21:54:58

Moja Intuicja :

Jeśli przyjmę wartość początkową jako 1 gdzie i=0, j=0, to Mogę tworzyć kolejne liczby jako (2^1)(5^0), (2^2)(5^0), (2^0)*(5^1), ... i. e 2,4,5 ..

Powiedzmy, że w dowolnym momencie moja liczba to x. następnie mogę tworzyć kolejne liczby w następujący sposób:

  • x * 2
  • x * 4
  • x * 5

Wyjaśnienie :

Since new numbers can only be the product with 2 or 5.
But 4 (pow(2,2)) is smaller than 5, and also we have to generate 
Numbers in sorted order.Therefore we will consider next numbers
be multiplied with 2,4,5.
Why we have taken x*4 ? Reason is to pace up i, such that it should not 
be greater than pace of j(which is 5 to power). It means I will 
multiply my number by 2, then by 4(since 4 < 5), and then by 5 
to get the next three numbers in sorted order.

Test Run

We need to take an Array-list of Integers, let say Arr.

Also put our elements in Array List<Integers> Arr.
Initially it contains Arr : [1]
  • Zacznijmy od x = 1.

    Następne trzy liczby to 1*2, 1*4, 1*5 [2,4,5]; Arr[1,2,4,5]

  • Teraz x = 2

    Następne trzy liczby to [4,8,10] {ponieważ 4 już zaszło będziemy ignoruj to} [8,10]; Arr[1,2,4,5,8,10]

  • Teraz x =4

    Następne trzy liczby [8,16,20] {8,16,20} [16,20] Arr[1,2,4,5,8,10,16,20]

  • X = 5

    Następne trzy liczby [10,20,25] {10,20} już tak [25] dodano Arr[1,2,4,5,8,10,16,20,25]

Warunek Zakończenia

 Terminating condition when Arr last number becomes greater 
 than (5^m1 * 2^m2), where m1,m2 are given by user.

Analiza

 Time Complexity : O(K) : where k is numbers possible between i,j=0 to 
 i=m1,j=m2.
 Space Complexity : O(K)
 0
Author: bharatj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-22 06:55:28

Po prostu byłem ciekaw, czego się spodziewać w przyszłym tygodniu i znalazłem to pytanie.

Myślę, że pomysł jest 2^i zwiększa Nie w tym duże kroki jak 5^j. więc zwiększyć i tak długo, jak następny j-krok nie będzie większy.

Przykład w C++ (Qt jest opcjonalny):

QFile f("out.txt"); //use output method of your choice here
f.open(QIODevice::WriteOnly);
QTextStream ts(&f);

int i=0;
int res=0;
for( int j=0; j<10; ++j )
{
    int powI = std::pow(2.0,i );
    int powJ = std::pow(5.0,j );
    while ( powI <= powJ  ) 
    {
        res = powI * powJ;
        if ( res<0 ) 
            break; //integer range overflow

        ts<<i<<"\t"<<j<<"\t"<<res<<"\n";
        ++i;
        powI = std::pow(2.0,i );

    }
}

Wyjście:

i   j   2^i * 5^j
0   0   1
1   1   10
2   1   20
3   2   200
4   2   400
5   3   4000
6   3   8000
7   4   80000
8   4   160000
9   4   320000
10  5   3200000
11  5   6400000
12  6   64000000
13  6   128000000
14  7   1280000000
 0
Author: Valentin Heinitz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-22 22:23:55

Oto moje rozwiązanie

#include <stdio.h>
#include <math.h>
#define N_VALUE 5
#define M_VALUE  5

int n_val_at_m_level[M_VALUE];

int print_lower_level_val(long double val_of_higher_level, int m_level)
{
int  n;
long double my_val;


for( n = n_val_at_m_level[m_level]; n <= N_VALUE; n++) {
    my_val =  powl(2,n) * powl(5,m_level);
    if(m_level != M_VALUE && my_val > val_of_higher_level) {
        n_val_at_m_level[m_level] = n;
        return 0;
    }
    if( m_level != 0) {
        print_lower_level_val(my_val, m_level - 1);
    }
    if(my_val < val_of_higher_level || m_level == M_VALUE) {
        printf("    %Lf n=%d m = %d\n", my_val, n, m_level);
    } else {
        n_val_at_m_level[m_level] = n;
        return 0;
    }
 }
 n_val_at_m_level[m_level] = n;
 return 0;
 }


 main()
 {
    print_lower_level_val(0, M_VALUE); /* to sort 2^n * 5^m */
 }

Wynik:

1.000000 n = 0 m = 0
2.000000 n = 1 m = 0
4.000000 n = 2 m = 0
5.000000 n = 0 m = 1
8.000000 n = 3 m = 0
10.000000 n = 1 m = 1
16.000000 n = 4 m = 0
20.000000 n = 2 m = 1
25.000000 n = 0 m = 2
32.000000 n = 5 m = 0
40.000000 n = 3 m = 1
50.000000 n = 1 m = 2
80.000000 n = 4 m = 1
100.000000 n = 2 m = 2
125.000000 n = 0 m = 3
160.000000 n = 5 m = 1
200.000000 n = 3 m = 2
250.000000 n = 1 m = 3
400.000000 n = 4 m = 2
500.000000 n = 2 m = 3
625.000000 n = 0 m = 4
800.000000 n = 5 m = 2
1000.000000 n = 3 m = 3
1250.000000 n = 1 m = 4
2000.000000 n = 4 m = 3
2500.000000 n = 2 m = 4
3125.000000 n = 0 m = 5
4000.000000 n = 5 m = 3
5000.000000 n = 3 m = 4
6250.000000 n = 1 m = 5
10000.000000 n = 4 m = 4
12500.000000 n = 2 m = 5
20000.000000 n = 5 m = 4
25000.000000 n = 3 m = 5
50000.000000 n = 4 m = 5
100000.000000 n = 5 m = 5
 0
Author: dhanasubbu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-09 18:37:38

Wiem, że prawdopodobnie się mylę, ale jest tu bardzo prosta heurystyka, ponieważ nie obejmuje wielu liczb, takich jak 2,3,5. Wiemy, że dla każdego i,j 2^i * 5^j Następna sekwencja będzie 2^(i-2) * 5^(j+1). Będąc google q musi mieć proste rozwiązanie.

def func(i, j):
 print i, j, (2**i)*(5**j)

imax=i=2
j=0
print "i", "j", "(2**i)*(5**j)"

for k in range(20):
    func(i,j)
    j=j+1; i=i-2
    if(i<0):
        i = imax = imax+1
        j=0

To daje wyjście jako:

i j (2**i)*(5**j)
2 0 4
0 1 5
3 0 8
1 1 10
4 0 16
2 1 20
0 2 25
5 0 32
3 1 40
1 2 50
6 0 64
4 1 80
2 2 100
0 3 125
7 0 128
5 1 160
3 2 200
1 3 250
8 0 256
6 1 320
 0
Author: d1val,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-17 19:13:07

Jeśli przejdziesz przez to, co naprawdę się dzieje, gdy zwiększamy i lub j w wyrażeniu 2^i * 5^j, to albo mnożysz przez kolejne 2 lub kolejne 5. Jeśli powtórzymy problem jako-biorąc pod uwagę szczególną wartość i I j, jak można znaleźć następną większą wartość, rozwiązanie staje się oczywiste.

Oto zasady, które możemy intuicyjnie wyliczyć:

  • Jeśli w wyrażeniu znajduje się para 2s (i > 1), powinniśmy zastąpić je przez 5, aby uzyskać następną największą liczbę. Tak więc, i -= 2 i j += 1.
  • w przeciwnym razie, jeśli istnieje 5 (j > 0), musimy zastąpić ją trzema 2. więc j -= 1 i i += 3.
  • w przeciwnym razie, musimy po prostu dostarczyć kolejne 2, aby zwiększyć wartość o minimum. i += 1.

Oto program w Ruby:

i = j = 0                                                                       
20.times do                                                                     
  puts 2**i * 5**j

  if i > 1                                                                      
    j += 1                                                                      
    i -= 2                                                                      
  elsif j > 0                                                                   
    j -= 1                                                                      
    i += 3                                                                      
  else                                                                          
    i += 1                                                                      
  end                                                                                                                                                               
end
 0
Author: slowpoison,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-12 17:17:42

Jeśli możemy używać kolekcji Javy, to możemy mieć te liczby w O (n^2)

public static void main(String[] args) throws Exception {
    int powerLimit = 7;  
     int first = 2;
     int second = 5;
    SortedSet<Integer> set = new TreeSet<Integer>();

    for (int i = 0; i < powerLimit; i++) {
        for (int j = 0; j < powerLimit; j++) {
            Integer x = (int) (Math.pow(first, i) * Math.pow(second, j));
            set.add(x);
        }
    }

    set=set.headSet((int)Math.pow(first, powerLimit));

    for (int p : set)
        System.out.println(p);
}

Tutaj powerLimit musi być zainicjowany bardzo ostrożnie !! W zależności od tego, ile liczb chcesz.

 0
Author: kavi temre,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-06 15:20:38

Oto moja próba ze scalą:

case class IndexValue(twosIndex: Int, fivesIndex: Int)
case class OutputValues(twos: Int, fives: Int, value: Int) {
  def test(): Boolean = {
    Math.pow(2,  twos) * Math.pow(5, fives) == value
  }
}

def run(last: IndexValue = IndexValue(0, 0), list: List[OutputValues] = List(OutputValues(0, 0, 1))): List[OutputValues] = {
  if (list.size > 20) {
    return list
  }

  val twosValue = list(last.twosIndex).value * 2
  val fivesValue = list(last.fivesIndex).value * 5

  if (twosValue == fivesValue) {
    val lastIndex = IndexValue(last.twosIndex + 1, last.fivesIndex + 1)
    val outputValues = OutputValues(value = twosValue, twos = list(last.twosIndex).twos + 1, fives = list(last.fivesIndex).fives + 1)
    run(lastIndex, list :+ outputValues)
  } else if (twosValue < fivesValue) {
    val lastIndex = IndexValue(last.twosIndex + 1, last.fivesIndex)
    val outputValues = OutputValues(value = twosValue, twos = list(last.twosIndex).twos + 1, fives = list(last.twosIndex).fives)
    run(lastIndex, list :+ outputValues)
  } else {
    val lastIndex = IndexValue(last.twosIndex, last.fivesIndex + 1)
    val outputValues = OutputValues(value = fivesValue, twos = list(last.fivesIndex).twos, fives = list(last.fivesIndex).fives + 1)
    run(lastIndex, list :+ outputValues)
  }
}

val initialIndex = IndexValue(0, 0)
run(initialIndex, List(OutputValues(0, 0, 1))) foreach println

Wyjście:

OutputValues(0,0,1)
OutputValues(1,0,2)
OutputValues(2,0,4)
OutputValues(0,1,5)
OutputValues(3,0,8)
OutputValues(1,1,10)
OutputValues(4,0,16)
OutputValues(2,1,20)
OutputValues(0,2,25)
OutputValues(5,0,32)
OutputValues(3,1,40)
OutputValues(1,2,50)
OutputValues(6,0,64)
OutputValues(4,1,80)
OutputValues(2,2,100)
OutputValues(0,3,125)
OutputValues(7,0,128)
OutputValues(5,1,160)
OutputValues(3,2,200)
OutputValues(1,3,250)
OutputValues(8,0,256)
 0
Author: nishnet2002,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-09 01:35:59