how to create three random numbers in javascript and then tell input is odd or not?
To determine if odd:
num % 2;
That will return 0 or 1. If you want it to return true or false, then do
(num % 2) == 1;
Make a "isOdd" function and you can use it to check your random numbers against:
function isOdd(num) {
return (num % 2) == 1;
}
Use it like
function randomizer() {
var a = Math.floor((Math.random() * 10));
var b = Math.floor((Math.random() * 10));
var c = Math.floor((Math.random() * 10));
if (isOdd(a)) {
\\Give more points because it's odd
}
}
Here's a very simple working example: https://codepen.io/anon/pen/rqLVxM
to verify that all numbers are even use this function
function areEven(a,b,c){
return a%2==0 && b%2==0 && c%2==0
}
to verify that all numbers are odd use this function
function areOdd(a,b,c){
return a%2!=0 && b%2!=0 && c%2!=0
}
to verify that all numbers are are in sequence use this function :
function areInSequence(a,b,c){
var array = [a,b,c];
array.sort(function(a, b){return a - b});
var validity=false;
var i;
var length = array.length
for (i =0; i < length-1 ; i++) {
if((array [i+1] - array [i]) == 1){
validity=true;
}else validity=false;
}
return validity;
}
combine this functions in your code and if you need help leave a comment thanks!
Hi am trying to generate random multiples of 100 using javascript.
I would expect the following to generate a random number between 1000 and 4000. Then check to see if it is a multiple of 100 and if so return it. And if not try generating another number.
I expected that in the else section of the if loop, rand() would just call the function again.
function rand() {
num = Math.floor(Math.random() * 4000) + 1000;
if (num % 100 == 0) {
return num;
} else {
rand();
}
}
Plunker: https://plnkr.co/edit/7tSGNiGQBUAYJsdMVeEr?p=preview
For the distances I am getting undefined instead of multiples of 100
I would expect the following to generate a random number between 1000 and 4000. Then check to see if it is a multiple of 100 and if so return it. And if not try generating another number.
To do that, you'd have to return the result of the recursive call to rand:
} else {
return rand();
}
But there's no need whatsoever to do that. To get random multiples of 100 in the range 1000 <= n < 4000:
return (Math.floor(Math.random() * 30 + 10)) * 100;
E.g., create a random number in the range 10 <= n < 40 and then multiply it by 100. :-)
Live Example:
function rand() {
return (Math.floor(Math.random() * 30 + 10)) * 100;
}
for (var n = 0; n < 100; ++n) {
console.log(rand());
}
.as-console-wrapper {
max-height: 100% !important;
}
Your method (generate any random number between 1000 and 4000 and only return multiples of 100) is 100 times slower than necessary and doing it recursively will probably crash the stack. Do a little elementary arithmetic:
function rand() { return 100 * Math.floor(30 * Math.random() + 10); }
You don't specify whether the 4000 is inclusive or not. If so, make that 30 above a 31.
You are simply missing a return statement, without it, the function is just run and when a match is found it's returned to nothing
function rand() {
num = Math.floor(Math.random() * 4000) + 1000;
if (num % 100 == 0) {
return num;
} else {
return rand(); //<-- here
}
}
console.log(rand())
Few things here 1, change your rand function to have a different range
num = Math.floor(Math.random() * (3000) + 1000);
Second, you are making a recursive function by calling it inside it self, for this you need to return the value to the past call function, if not the value stays on the last succesfull call.
else {
num = rand();
return num;
}
Hope this helps :>
function rand() {
let num = Math.floor(Math.random() * (3000) + 1000);
if (num % 100) {
num = rand();
}
return num;
}
console.log(rand());
all!
I'm new to programming and trying to write a while loop that will return the product of all numbers 1 to n, inclusive. I can't get my code to work properly; it keeps returning weird numbers.
I think the problem is with the first line of the while loop. It's like it's not multiplying, but I don't know why.
Here is the code I wrote:
var n = 7;
var multiplier = 1;
while (multiplier <= n){
multiplier = (multiplier * multiplier+1);
if (n < 6){
multiplier+= 2;
}
else {
multiplier++;
};
};
console.log(multiplier);
The problem is your use of the multiplier variable, you are using it to store the result, instead you need to use a separate variable to store the result and use it as a counter variable like
var n = 5;
var multiplier = 1;
var result = 1;
while (multiplier <= n) {
result *= multiplier++;
};
document.body.innerHTML = (result);
If you look at your loop below, at the end of 1st iteration multiplier is 3, end of second loop it is 11 which is higher than 7 so the loop exists.
var n = 7;
var multiplier = 1;
while (multiplier <= n) {
multiplier = (multiplier * multiplier + 1);
if (n < 6) {
multiplier += 2;
} else {
multiplier++;
};
snippet.log('loop: ' + multiplier)
};
snippet.log('result: ' + multiplier);
<!-- To show result in the dom instead of console, only to be used in the snippet not in production -->
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
How can I generate a random number between 1 - 10 except that the random number can't be 3
Get a random number between 1 and 9 and then add one if it's 3 or greater, or
better, just change any 3s into 10s.
function getNumber() {
return (n = 9 * Math.ceil(Math.random())) === 3? 10: n;
}
Based on this nice answer:
function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var rand;
while((rand = getRandomInt(1, 10)) == 3);
// rand is now your random number
function rand(begin, end) {
var result = Math.floor( Math.random() * (end - begin + 1) ) + begin;
return result === 3 ? rand(begin, end) : result;
}
function rand(){
var r = Math.ceil(Math.random() * 10);
if (r==3){
return rand()}
else
return r;
}
Here's a short, quick solution, using a self-executing function, that does what you need exactly but is only useful for the specific circumstance you describe:
var randOneToTenButNotThree = function () {
var result = Math.floor(Math.random() * 10) + 1; // PICK A NUMBER BETWEEN 1 AND 10
return (result !== 3) ? result : randOneToTenButNotThree(); // IF THE NUMBER IS NOT 3 RETURN THE RESULT, OTHERWISE CALL THIS FUNCTION AGAIN TO PICK ANOTHER NUMBER
}
var result = randOneToTenButNotThree(); // RESULT SHOULD BE A NUMBER BETWEEN 1 AND 10 BUT NOT 3
However, you could abstract this out to produce a random number in any given range, excluding any number of your choice:
var randExcl = function (lowest, highest, excluded) {
var result = Math.floor(Math.random() * (highest - lowest)) + lowest;
return (result !== excluded) ? result : randExcl();
}
var result = randExcl();
Just don't forget that if the function is renamed, you should also change the reference to it from within at the end of that return statement so that it can keep calling itself whenever it produces the excluded number.
This should work.
var r = 3;
while(r == 3) r = Math.ceil(Math.random() * 10);
function r(){a = Math.floor(Math.random() * 10) + 1; if (a==3) a++; return a;}
I have the following code but it is not giving perfect result for factorial can u find it out plz
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title> New Document </title>
<script type="text/javascript">
function fact(num)
{
var x=parseInt(num);
//alert(x+1);
if(x>0)
x=x* fact(x-1);
alert(x);
}
</script>
</head>
<body>
<form name="f1">
Enter the Number :<input type="text" length="8" name="txt1"><br>
<input type="button" value="Find factiorial" onclick="fact(txt1.value)">
</form>
</body>
</html>
You have to return the value. Here you go:
function fact(x) {
if(x==0) {
return 1;
}
return x * fact(x-1);
}
function run(number) {
alert(fact(parseInt(number, 10)));
}
and
<input type="button" value="Find factiorial" onclick="run(txt1.value)">
(How to make it work for negative numbers I leave up to you ;) (but I showed in this post anyway))
Just for fun, a more correct, non recursive algorithm:
function fact(x) {
if(x == 0) {
return 1;
}
if(x < 0 ) {
return undefined;
}
for(var i = x; --i; ) {
x *= i;
}
return x;
}
Use loop its easy to implement
function fact(num)
{
if(num<0)
return "Undefined";
var fact=1;
for(var i=num;i>1;i--)
fact*=i;
return fact;
}
<input type="button" value="Find factiorial" onclick="alert(fact(6))">
function factorial(n) {
return (n != 1) ? n * factorial(n - 1) : 1;
}
alert( factorial(5) );
You can try to use recursion method
Your function doesn't return anything, ever.
What do you do when x is 0?
Minor point - apart from alert, you don't really do anything with the returned value.
Try this instead, if you will (hover over the text):
if(x==0) return 1;
return x * fact(x-1);
Working example: http://jsbin.com/apuka3/2
You need to have a return in your function in the first place. ;)
I wrote this and it works.
var d = 1;
for (num; num > 1; num--) {
d *= num;
}
return d;
Here's a short recursive version:
function doFact(n) {
return +!(+(n)) || doFact(n - 1) * n;
}
function factorialFromInput() {
var theInputVal = document.getElementsByTagName("input")[0].value;
var theContainer = document.getElementById("resultContainer");
theContainer.innerHTML = "" + doFact(Math.abs(theInputVal));
}
.wrapper>* {
line-height: 2em;
width: 30%;
}
#resultContainer {
border: outset grey;
min-height: 1.1em;
padding-left: 0.3em;
background-color: #eff0f1;
overflow: scroll;
}
<div class="wrapper">
<input type="text" id="valEntered">
<br>
<button onclick="factorialFromInput();">Calculate Factorial</button>
<br>
<div id="resultContainer"></div>
</div>
function fact(n) {
if (n > 1) {
return n * fact(n-1);
} else {
return 1;
}
}
console.log(fact(5));
Using ternary operator we replace the above code in a single line of code as below
function fact(n) {
return (n != 1) ? n * fact(n - 1) : 1;
}
console.log(fact(5));
This is the very easiest way and latest JS(ES6)
factorial = n => n - 1 > 0 ? n * factorial(n - 1) : n;
//output
console.log(factorial(5));
Here I used ES6 arrow function. For better understanding please see what is arrow function.
Recursion in JS is open to stack overflow error and also very slow. Looping by other means is better. My contribution to factorial code would be a straightforward one;
var fact = n => n > 0 ? Array.from({length: n}, (_,i) => i+1)
.reduce((p,c) => p*c)
: 1;
console.log(fact(5));
The important part of the function is this line:
x = x * fact(x-1);
but the fact function does not return a value, so this is the same as x * undefined. Try adding return x; to the bottom of your function.
1) When X=0 function should return 1;
2) Added return;
function fact(num)
{
var x=parseInt(num);
//alert(x+1);
if(x>0)
x=x* fact(x-1);
else
x=1;
return x;
}
usage
<input type="button" value="Find factiorial" onclick="alert(run(fact.value));">
A slight edit to Anton's code:
function fact(x) {
if(x>0)
return x* fact(x-1);
if(x===0)
return 1;
return null;
}
(factorial of a negative doesn't exist, but factorial of 0 is equal to 1, in this case, if a number is smaller than 0, the function will return null)
What about:
function fact(n) {
n = Math.round(n);
if (n < 2) {
return 1;
}
else {
return n * fact(n - 1);
}
}
?
My suggestion:
function fact(x) {
if (x<0) {
return Infinity
};
var _= 1
for ($=1;$<=x;++$) {
_*=$
};
return _
};
It simply returns the factorial of whatever "x" is.
Here is one I made using a while loop:
function factorialize(num)
{
i = 1;
b = 1;
while (i < num) {
b = b + (b * i);
i = i + 1;
}
return b;
}
<script src="jquery-3.1.0.js"></script>
<script>
$(function () {
var target = 5;
var factorial = 1;
for (var i = 1; i <= target; i++) {
factorial *= i;
}
alert(factorial);
});
</script>
you can set any value in target and this logic will calculate Factorial.
Thanks... :)
I am not sure why no one used dynamic programming to answer this, it's by far the most efficient way to build something on a factorial in my view.
var mem = [];
function fact(num)
{
var x = parseInt(num);
if (x == 0 || x == 1) return 1;
mem[x] = x * fact(x-1);
return mem[x];
}
a very simple form:
function fact() {
var x = document.getElementById("txtf").value;
var f=1;
for (var i=1; i <= x ; i++){
f = f*i;
}
document.getElementById('showR').innerHTML= f;
}
<input type="text" id="txtf" value="3">
<input type="button" id="btnf" value="click for calculate" onclick="fact()">
<p id="showR">/Factoriel/</p>
function factorial(num) {
var result = 1;
for (var i = 1; i <= num; i++) {
result = result * i;
}
return result;
}
//call function e.g factorial(4).. 1*2*3*4 it will evaluate in ascending order
var factorialNumber , factorial=1;
factorialNumber=prompt("Factorial Number" , "write Factorial Number");
for(var i = 1; i<= factorialNumber;i++){
factorial *= i;
}
alert(factorial);
The code above first defines two variables, factorialNumber and factorial. factorial is initialized with 1. factorialNumber will get the result of the prompt (a number is expected) and then, using a cycle, in each step, factorial is multiplied with the index of the step, which is represented by i. When successfully calculated, we show the result using alert.
With a Do loop, it is pretty easy.
<table>
<tr>
<th>Amount of integers</th>
<th>Answer</th>
</tr>
<tr>
<th><input id="int" type="number"/></th>
<th><input id="answer" type="number"/></th>
</tr>
</table>
<button onclick="calculate()">calculate</button>
<script>
function calculate() {
var input = document.getElementById("int").value;
var int = 1;
do {
var product = int *= input;
input--;
} while (input > 0);
answer.value = product;
}
</script>
You first set a table to act as a way to input your variable and have a place to output the answer. You also add a button to execute your function.
The input variable is the value entered by the user. You also have int variable as a placeholder.
Inside the do loop you then another variable that is the product, it takes your placeholder variable and times it by the input. After this the input decrements, as long as input value is then greater than zero the loop keeps iterating.
Then at the end, it posts the answer to the 'answer' id tag in the table.
function factorial (n) {
if (n > 1) {
return n * factorial(n-1);
}
return 1;
}
console.log("recursive way => ",factorial(5));
function factorial(num){
if(num<1||typeof num!=='number'){
return undefined
}
if(num===1){
return num
}
return num*factorial(num-1)
}
console.log(factorial(3))
https://jsfiddle.net/mohittadhiyal/6w64x0sL/10/
I've seen a recursive approach used in many places (Eloquent JavaScript etc). Here, the function is called recursively until it reaches 0, which should not be the case. We should only call the function till it is >= 2 because the last number we need to multiply by is 1.
It's a very minor change, and probably does not matter. Curious to know what other people think of it. Assuming it is a valid positive integer.
/**
* Popular approach - the recursive function is called till x is 0
*
* #param x
*/
function popularFactorial(x) {
console.log(x)
if(x === 0) {
return 1
} else {
return x * popularFactorial(x - 1)
}
}
var result = popularFactorial(8)
console.log(result)
/**
* Using this approach, the recursive function is called one less time
* i.e till x is 1
*
* #param x
*/
function factorial(x) {
console.log(x)
if(x === 0) {
return 1
} else if(x >= 2) {
return x * factorial(x - 1)
}
return x
}
var result = factorial(8)
console.log(result)
function factorial(n) {
return [...Array(n + 1).keys()].slice(1).reduce((total, currentValue) => total * currentValue, 1);
}
//This is fastest way to implement factorial
const fact = n => !n ? 1 : n * fact(--n);
console.log(fact(10))
i am quite new to javascript and would be happy to know any improvements that could be made to this answer
var a = 1;
function factorial(num) {
if (num == 0) {
return 1;
} else if (num < 0) {
return undefined;
} else {
for(i = num; i > 0; i--){
a *= i;
}
return a;
}
}
var b = factorial(5);
console.log(b);