Float to String Conversion - JS - javascript

So I am currently working on that function
const countSixes = n => {
if (n === 0) return 0;
else if (n === 1) return 1;
else n = (countSixes(n-1) + countSixes(n-2)) / 2;
return n;
}
And so my question is how to convert the final floating-point value into a string?
Every time after calling the function and trying to convert the float number it returns NaN
What I've Tried
"" + value
String(value)
value.toString()
value.toFixed(2)
Hope to get the answer
Thank you!

The first option works for me
<script>
const countSixes = n => {
if (n === 0) return 0;
else if (n === 1) return 1;
else n = (countSixes(n-1) + countSixes(n-2)) / 2;
return n;
}
alert(countSixes(12) + "")
</script>

The problem is really interesting. Its return NaN because when you return n as String, as the function is called recursively so it cannot perform arithmetic operations in next level.
It will never end for certain numbers like 55
function countSixes(n,firstTime=true){
if (n === 0) return 0;
else if (n === 1) return 1;
else n = (countSixes(n-1,false) + countSixes(n-2,false)) / 2;
if(firstTime) return n.toFixed(10); // return string
else return parseFloat(n.toFixed(10)); // return float
}

You could convert the final value to a string with the wanted decimals.
const countSixes = n => {
if (n === 0) return 0;
if (n === 1) return 1;
return (countSixes(n - 1) + countSixes(n - 2)) / 2;
}
console.log(countSixes(30).toFixed(15));

Related

Recursion is 4 but the expected output is 64

let power2 = (x,n) => {
if(n == 0) return 1;
let temp = power2(x,n/2);
if(n%2 == 1) return temp * temp * x;
return temp*temp;
}
console.log(power2(4,3));
This method has less nodes and time complexity but its giving wrong output
The problem with the original code was the fact that n / 2 will result in a real number when you need it to be treated as an integer. Bitwise operation are always performed on integers so n >> 1 will correctly yield an integer. The same goes with modulo which converts the number to an integer first that's why it worked correctly in your code.
let power2 = (x, n) => {
if (n === 0) return 1;
const temp = power2(x, (n >> 1));
if (n % 2 === 1) return temp * temp * x;
return temp * temp;
}
console.log(power2(4, 3));
If you need custom integer power function, based on recursion, consider this snippet:
// Custom pow
const myPow = (n, i) => i > 0 ? myPow(n, i - 1) * n : 1;
// Test
console.log(myPow(4, 3));

How to return NaN

I'm working on a codewars problem-here's the question:
-Write a function that accepts two integers and returns the remainder of dividing the larger value by the smaller value.
-Division by zero should return NaN.
I have the first part figured out, but how do I return NaN if I divide by 0? I don't know a lot about NaN and I'm pretty new to JavaScript.
function remainder(n, m){
if (n > m) {
let answer = n % m;
if (m === 0) {
return undefined;
}
else {
return answer;
}
}
else if (m > n) {
let answer = m % n;
if (n === 0) {
return undefined;
}
else {
return answer;
}
}
else {
let answer = n % m;
return answer;
}
}
Edit: solved, answer is below
Welcome to our community!
NaN stands for Not-a-Number and it is a property of the global object(in order to understand more about the global object, I would recommend reading about Scopes).
You could access NaN like this:
window.NaN => from a browser
Number.NaN
NaN
If you want to check if a number is NaN you could use: isNaN.
If you want to use it in a function you can just do
function test(x){
if(isNaN(x)){
return NaN;
}
return x;
}
To come back to your problem, you could do something like this:
function calculateRemainder(a,b){
return a>b ? a % b : b % a
}
Where % is known as the remainder operator about which you can read more here. This operator returns NaN if you try to divide by 0 or to operate with Infinity.
The following operations return NaN:
NaN % 2
Infinity % 0
10 % 0
Infinity % Infinity
The problem is that % is not the divider syntax, but this is /.
I created a basic example for you:
In this example, the console logs "divider is 0"
function divider(up, down) {
if (down == 0) {
console.log("divider is 0");
return NaN
} else {
console.log(up / down);
}
}
divider(5, 0);
But here, it will log 2.5
function divider(up, down) {
if (down == 0) {
console.log("divider is 0");
return NaN
} else {
console.log(up / down);
}
}
divider(5, 2);
This is my answer (with help from the comments on my question), and it worked. Thank you for your help!
function remainder(n, m){
if (n > m) {
let answer = n % m;
if (m === 0) {
return NaN;
}
else {
return answer;
}
}
else if (m > n) {
let answer = m % n;
if (n === 0) {
return NaN;
}
else {
return answer;
}
}
else {
let answer = n % m;
return answer;
}
}

How to express recursive calls in higher dimensions

Just a question of curiosity, not serious.
In the JS language I know that a factorial operation can be defined in the following form.
function factorial(n) {
if (n === 1) return 1;
return factorial(n - 1) * n;
}
Then I defined a factorial of a factorial operation in the following form, and called it super_factorial_1. There is a similar description on Wikipedia.
function super_factorial_1(n) {
if (n === 1) return factorial(1);
return super_factorial_1(n - 1) * factorial(n);
}
Similarly, using the super_factorial_1 as an operator, the super_factorial_2 is defined here:
function super_factorial_2(n) {
if (n === 1) return super_factorial_1(1);
return super_factorial_2(n - 1) * super_factorial_1(n);
}
Now the question is how to define the super_factorial_n operation, and the super_factorial_n_n, and furthermore, the super_factorial_n..._n{n of n}.
I have used a crude method to define the above super_factorial_n operation, but I don't think this method is good enough.
function super_factorial_n(n, m) {
const fns = Array(n + 1).fill(0);
fns[0] = factorial;
for (let i = 1; i <= n; i++) {
fns[i] = function (m) {
if (m === 1) return fns[i - 1](1);
return fns[i](m - 1) * fns[i - 1](m);
}
}
return fns[n](m);
}
Perhaps this is an optimisation direction for the process programming paradigm. :)
The pseudo code
// j is the level number
// i = j - 1
function super_factorial_j(n) {
if (n === 1)
return super_factorial_i(1);
return super_factorial_j(n - 1) * super_factorial_i(n);
}
Parameterize the j and i
function super_factorial(j, n) {
if (n === 1)
return super_factorial(j - 1, 1);
return super_factorial(j, n - 1) * super_factorial(j - 1, n);
}
Add the exit condition
function super_factorial(j, n) {
if (j == 0) { // or j == 1 for one based level number
if (n === 1)
return 1;
return super_factorial(0, n - 1) * n;
}
if (n === 1)
return super_factorial(j - 1, 1);
return super_factorial(j, n - 1) * super_factorial(j - 1, n);
}
Of course this is just one of the many ways to go. And it is hard to say if this is better then any other one. Recursive functions are generally stack memory consuming. But the value are likely grow very fast, it is not very practice to call it with big numbers anyway.

Using a recursive function to find the factorial of a given integer

I'm trying to make a recursive function to print the factorial of a given integer. Ask the user to enter a positive integer and then display the output on a page. For example, if the user enters 5, the output must be
5 × 4 × 3 × 2 × 1 = 120
var integer = prompt("Enter a positive integer.");
function factorialize(num) {
if(num == 0 || num == 1) {
return 1;
}
else {
return num + " x " + factorialize(num-1) + num * factorialize(num-1);
}
}
document.write(factorialize(integer));
You can pass a runningTotal of the sum so far to each recursive call. You can also keep the solution compact using template literals.
function factorialize(n, runningTotal = 1) {
if (n === 1) return `1 = ${runningTotal}`;
return `${n} x ${factorialize(n - 1, runningTotal * n)}`;
}
console.log(factorialize(5));
You could handover the parts of product and result.
function factorialize(num, product = 1, result = '') {
return num === 0 || num === 1
? result + (result && ' x ') + num + ' -> ' + product
: factorialize(num - 1, product * num, result + (result && ' x ') + num);
}
console.log(factorialize(5));
console.log(factorialize(2));
console.log(factorialize(1));
console.log(factorialize(0));
I think make that recursively is quite confused:
function factorialize(n, expression = '', result = 0) {
if (n < 0) {
return null
} else if (n === 0) {
return (expression || n) + " = " + result
}
const newExpression = result ? expression + " x " + n : n
const newResult = !result ? n : result * n
return factorialize(n - 1, newExpression, newResult)
}
console.log(factorialize(5))
Is better to segregate the responsibilities:
function factorial(n) {
let fact = 1
if (n < 0) {
console.warn("Error");
return 0
} else {
for (let i = n; i > 0; i--) {
fact = fact * i;
}
}
return fact
}
function factorialExpression(n) {
let expression = ""
if (n < 0) {
console.warn("Error");
return ""
} else {
for (let i = n; i > 0; i--) {
expression += (i < n ? " x " : "") + i
}
}
return expression
}
function factorialize(n) {
if (n === 0 || n === 1) {
return n + " = " + n
} else if (n > 1) {
return factorialExpression(n) + " = " + factorial(n)
}
return null
}
console.log(factorialize(5))

Javascript - Better Alternate to Recursive call

I have this following problem.
I need to calculate a number x based on time t, x would be represented as M(t).
We have the following
M(0) = 1
M(1) = 1
M(2) = 2
M(2t) = M(t) + M(t + 1) + t (for t > 1)
M(2t + 1) = M(t - 1) + M(t) + 1 (for t >= 1)
With that being said the first thing i had in mind to implement this is by using recursion
function CalculateForTime(t) {
if (t == 0 || t == 1) {
return 1;
}
else if (t == 2) {
return 2;
}
else if (t % 2 == 0) {
t = t / 2;
return CalculateForTime(t) + CalculateForTime(t + 1) + t;
}
else {
t = (t - 1) / 2;
return CalculateForTime(t - 1) + CalculateForTime(t) + 1;
}
}
This works however it breaks when running on a large number t for example 1^20
I tried looking into tail call recursion or substituting the recursion approach to an iteration approach but couldn't really figure it out.
If tail recursion or iteration is the way to go then please I need help on converting this. If not then I'm open to different methods on making this more optimized.
Thank you,
Omar.
You could use a hash table, because for an array it would generate holes with no value.
function calculateForTime(t) {
var k = t;
if (k in lookup) {
return lookup[k];
}
if (t == 0 || t == 1) {
return lookup[k] = 1;
}
if (t == 2) {
return lookup[k] = 2;
}
if (t % 2 == 0) {
t = t / 2;
return lookup[k] = calculateForTime(t) + calculateForTime(t + 1) + t;
}
t = (t - 1) / 2;
return lookup[k] = calculateForTime(t - 1) + calculateForTime(t) + 1;
}
var lookup = {};
console.log(calculateForTime(1e10));
.as-console-wrapper { max-height: 100% !important; top: 0; }
You could store the values in an array,then theres no need to recalc...
var times=[1,1,2];
function CalculateForTime(t) {
t = Math.floor(t / 2);
return times[t]||(times[t]=CalculateForTime(t) + CalculateForTime(t + 1) + t);
}
console.log(
CalculateForTime(100),
CalculateForTime(1000),
CalculateForTime(10000),
);
console.log(times.slice(0,100));
You could use memoization to avoid recalculating the same values again and again. See https://addyosmani.com/blog/faster-javascript-memoization/
This is the same as what others suggested, except that it separates the algorithm from the caching of values.
function memoize(func){
var cache = {};
return function( arg ){
if(arg in cache) {
return cache[arg];
} else {
return cache[arg] = func( arg );
}
}
}
// Overwrite with a function that remember previous results
CalculateForTime = memoize(CalculateForTime);
Pardon any typos, answered from phone

Categories