Time limit exceeded and the answer was skipped - double

This is my code to find factorial inverse
double num;
cin>>num;
double i=1,fact=1;
for(i=1;i>0;++i)
{
fact*=i;
if(fact==num)
{
cout<<i;
break;
}}
But when i put the factorial of 28 the loop became infinite.
When i output fact to check the loop, the answer was output among other factorial numbers but the loop kept going after the right factorial of 28.
It works up to 27! .

Related

Stuck In Run Mode Jupyter Notebook

My Jupyter Notebook gets stuck in run mode whenever i run the shell with the following code:
def is_prime(num):
if num < 2:
return False
for x in range(2, num - 1):
if num % x == 0:
return False
return True
prime_list = []
num = 2
while True:
if is_prime(num):
prime_list.append(num)
num += 1
if len(prime_list) == 10002:
break
print(prime_list[-1])
Could someone please run this code on their computer and tell me what the output is? I'd really appreciate any answer.
Your code is getting stuck because your prime testing function becomes very slow!
I ran your code with varying stopping points of 100, 1000, 2000, and 4000 prime numbers found. The runs took 0.01, 0.23, 0.98, and 4.31 seconds, respectively.
You can see that doubling the number of primes to find (roughly) quadruples the amount of time taken. This makes sense, given that to test if n is prime, you have to check it against n-2 other numbers (you exclude 1 and n). So, your algorithm has a time complexity of at least O(n^2) to find n prime numbers.
(also, I got 104759 after 10002 prime numbers were found in 30 seconds. I accidentally typed "100002" at first, which sat running for quite a long time without any results...)

Why is while loop much slower than for loop in Swift?

I'm trying to evaluate the performance of these two loop method, I tried number from 0 to 99999 using for in and while loop clause.
for i in 0..<s.count - 9 {
print("\(i)")
}
var j = 0
while j < s.count - 9 {
print("\(j)")
j = j+1
}
In both loop, will print the current number and add number by 1 until it reaches 99999.
Turns out that for in clause use 0.91 to go through every number, at same time while take much much much longer time (around 80.8).
I searched on Internet and documents, but cannot figure out why.
What cause this huge performance difference?

simple recursive function error - java.lang.StackOverFlow error - output exceeds cut off limit

I am practicing scala's simple recursive function. This is from a book
def calculatePower(x:Int, y:Int): Long = {
if (x>=1)
x*calculatePower(x,y-1)
else 1
}
calculatePower(2,2)
You are checking x but you are decrementing y. That means your base-case will never be reached.
Your method stack overflows because it doesn't terminate and the stack frames accumulates until there is no more room.
if (x>=1) x*calculatePower(x,y-1) You test if x is greater or equal to 1 but in the recursive call you only decrement y!

While loop in CoffeeScript

I'm new to CoffeeScript and have been reading the book, The Little Book on CoffeeScript. Here are a few lines from the book's Chapter 2 which confused me while reading :
The only low-level loop that CoffeeScript exposes is the while loop. This has similar behavior to the while loop in pure JavaScript, but has the added advantage that it returns an array of results, i.e. like the Array.prototype.map() function.
num = 6
minstrel = while num -= 1
num + " Brave Sir Robin ran away"
Though it may look good for a CoffeeScript programmer, being a newbie, I'm unable to understand what the code does. Moreover, the words returns an array of results doesn't seem to go together with the fact that while is a loop construct, not a function. So the notion of it returning something seems confusing. Furthermore, the variable num with the string "Brave Sir Robin ran away" in every iteration of the loop seems to be awkward, as the value num is being used as the loop counter.
I would be thankful if you could explain the behavior of the code and perhaps illustrate what the author is trying to convey with simpler examples.
Wow! I didn't know that but it absolutely makes sense if you remember that Coffeescript always returns the last expression of a "block".
So in your case it returns (not via the "return" statement if that is what confuses you) the expression
num + " Brave Sir Robin ran away"
from the block associated with the while condition and as you will return multiple such expressions it pushes them on an array.
Have a look on the generated JavaScript and it might be clearer as the generated code is pretty much procedural
var minstrel, num;
num = 6;
minstrel = (function() {
var _results;
_results = [];
while (num -= 1) {
_results.push(num + " Brave Sir Robin ran away");
}
return _results;
})();
I hope that makes sense to you.
Beware, that function call can be very inefficient!
Below is a prime factors generator
'use strict'
exports.generate = (number) ->
return [] if number < 2
primes = []
candidate = 1
while number > 1
candidate++
while number % candidate is 0
primes.push candidate
number /= candidate
candidate = number - 1 if Math.sqrt(number) < candidate
primes
This is the version using while as expression
'use strict'
exports.generate = (number) ->
return [] if number < 2
candidate = 1
while number > 1
candidate++
primes = while number % candidate is 0
number /= candidate
candidate
candidate = number - 1 if Math.sqrt(number) < candidate
primes
First version ran my tests in 4 milliseconds, the last one takes 18 milliseconds. I believe the reason is the generated closure which returns the primes.

Multiply a number by 2 in Brainfuck?

Given an arbitrarily long number, how can I output its double? I know how to multiply small numbers together as long as the result is <10, but what about larger integers like 32984335, and doubling something like that? I don't know the right way to handle something like this.
This is the algorithm you need to implement:
Start the current count with 0;
Multiply the current count by ten: this can be achieved by dupping 10 times, and then adding all dupes together;
Read a digit;
If it's null proceed to 8;
Convert it to an actual number: this can be achieved by subtracting 48;
Add it to the current count;
Proceed to 2;
Duplicate the current count;
Adding the dupes together;
Divide by ten using repeated subtraction; keep quotient and remainder;
Grab the remainder;
Make it a digit (add 48);
Print it;
Grab the quotient from 10;
If it's not zero, goto 10;
The end.
All these steps consists of basic brainfuck idioms, so it should be easy to implement.
Here's a start. It will multiply a byte of input, but I think you can build off it to make it work for any number. Basically, you take in a number, and store the number to multiply by (2) in the next pointer. You loop decrementing the first number, and then nest a loop decrementing the second number; in each iteration of the inner loop, you increment the pointer to the right of your second operand. This is your result.
, take input to ptr 0
[
- decrement first operand (input)
>++ number to multiply by (2) at ptr 1
[
>+ result in ptr 2
<- decrement second operand (2)
]
<
]
>> move to result
Here is my BF code: http://ideone.com/2Y9pk8
->>+>,+
[
-----------
[
-->++++++[-<------>]<
[->+<[->+<[->+<[->+<[>----<-<+>[->+<]]]]]]>
[-<++>]<+
>,+
[
-----------
[->+<]
]
>[-<+>]<
]
<[<]
>-[<++++++++[->++++++<]>.[-]]
>[<++++++++[->++++++<]>-.[-]>]
++++++++++.[-]
<+[-<+]
->>+>,+
]
It reads each number in each line until EOF, and multiply all numbers by two..
Here is the code for multiplying a number by 2.
,[>++<-]>.
Hope this helps.