I had an interview question the day before yesterday
Please use js, python, java, c, c and other languages to calculate 10 billion data in 10 seconds, and complete it (only within 3 seconds), even number Before the odd number
the format is as follows
1, 2, 3, 4, 5
The output result is
2, 1, 4, 3, 6, 5,
Question 2: In 1 Above the code, it is required not to use the for while keyword and to get all the prime numbers from 10 billion (the time cannot exceed 3 seconds)
How to do this?
I don’t understand the first question. Does it mean that 2 numbers are a pair, and the even number comes before the odd number?
The second question is simple. If you can’t use a loop, then use array iteration.
By the way,
php
’sforeach
doesn’t count (laughsI think the interviewer’s intention is to ask you to write a recursive function? Well I guess so.
Since it cannot be used for while
Then the recursive performance is not enough. . . But I still use some. .
For Performance
There may be a clever way
. . . There should be a size of
10 billion
. I haven't found it yet.Code
10 billion is a bit big, I’ll take 100,000 first
In this way, you can get an array of natural numbers with a length of 100,000.
Next
Even numbers first, odd numbers last
After observation, we found that
odd number + 1
,even number - 1
is fineComplete the first question
ScreenShot One
Next
The next question is to get the prime numbers based on the above, that is, get all the prime numbers from
zs
I checked the question about prime numbers, and others said
Primes are distributed on the left or right of multiples of 6
Then I just need to traverse the left and right of each multiple of 6 and determine whether they are prime numbers.Link: Determining whether a number is a prime number/prime number - from ordinary judgment algorithm to efficient judgment algorithm idea
ScreenShot Two
I don’t know if it’s right...
But we still need to piece together the prime numbers
less than 6
1 2 3 5 separately. (No spelling here)Performance
Adhere the code written above
test
10 million
The result is as shown in the pictureIt took
13.8
seconds. It is impossible to complete10 billion
in10 + 3
seconds.My computer is
i5-4210M
12G
Chrome 58
JavaScript
cannot achieve this performance:10 billion
numbers13
seconds....Data from several
G
...According to the above idea, even
C/C++
is estimated to be difficult to run 10 billion in 13 seconds.Focus on solving problems.
Links
Determine whether a number is a prime number/prime number - from ordinary judgment algorithm to efficient judgment algorithm idea
First of all, thanks to the algorithm for finding prime numbers upstairs. I will post my results and code (only 10 million, 100 million browsers directly exploded, and recursion cannot be used to find prime numbers (results of my test), otherwise it will be Exploded, can only iterate).
Results in browser:
The result innode: