I need to write a program that takes two integers base and exponents and compute the exponents without using Math.Pow(). I have created the code using the Math.pow() method I can't figure out how to make it work without it. I have tried base^exp but it doesn't give me the right answer. Thanks in advance!
/* Write a JavaScript function named intPow that reads two numbers named base and exp from two text fields. Assume that the second number will always be an integer greater than or equal to 1. Your function should not use any of the built in Math functions such as Math.pow. Your function should use a loop to compute the value of baseexp meaning base raised to the power of exp. Your function must output the result of baseexp to a div. Hint: write your function to compute 1 multiplied by base exp times. */
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Integer Power</title>
<script type="text/javascript">
/* Write a JavaScript function named intPow that reads two numbers named base and exp from two text fields. Assume that the second number will always be an integer greater than or equal to 1. Your function should not use any of the built in Math functions such as Math.pow. Your function should use a loop to compute the value of baseexp meaning base raised to the power of exp. Your function must output the result of baseexp to a div. Hint: write your function to compute 1 multiplied by base exp times. */
function intPow() {
var base = parseFloat(document.getElementById("baseBox").value);
var exp = parseFloat(document.getElementById("expBox").value);
var output = "";
var i = 0;
for (i = 1; i <= exp; i++) {
output = Math.pow(base, exp);
}
document.getElementById("outputDiv").innerHTML = output;
}
</script>
</head>
<body>
<h1>Find the power of <i>Base</i> by entering an integer in the <i>base</i> box, and an integer in the <i>exponent</i> box.</h1> Base:
<input type="text" id="baseBox" size="15"> Exponents:
<input type="text" id="expBox" size="15">
<button type="button" onclick="intPow()">Compute Exponents</button>
<div id="outputDiv"></div>
</body>
</html>`
For anyone looking this up in the future, such as me just now, this is a solid solution:
function computePower(num, exponent) {
var result = 1;
for (i = 0; i < exponent; i++) {
result *= num;
}
return result;
}
Given a number and an exponent, "computePower" returns the given number, raised to the given exponent.
#user5500799,
output = (1 * base ) * exp;
won't work, because you are not raising the base to the exponent, just multiplying it. Starting with a multiplication with 1 is great though: in my code, that ensures that, for example, 2 to the power of 0 is 1 (everything to the power of 0 is one, which is something that is defined)
with ES2016 you can use the exponentiation operator.
2 ** 8 // 256
I was able to figure it out by changint output to:
output = (1 * base ) * exp;
Related
I have just started learning Javascript. I am doing the course in Viope World. I need to get two different numbers, but each time, I get the same number for the num and exponent variables, while the function calcPower is correct. I don't understand how to get different inputs in the function fetchValue() without having HTML for this task. I have tried using the method Document.querySelector() and other things which shouldn't be complicated for such an exercise.
These are the requirements:
Fill in the missing functions fetchValue(id) and calcPower(base, exponent). The function fetchValue(id) looks for a HTML text input element and returns its value. The function calcPower(base, exponent) has to calculate and return a number based on the values passed to it. Note that all of the printing happens within the pre-made section of the program.
This is the part of the code I can't change:
function calcFunc(){
var num = fetchValue("num");
var exponent = fetchValue("exponent");
console.log("The number " + num + "to the power of " + exponent + " is:");
console.log(calcPower(num, exponent));
}
My code:
function fetchValue(id){
let val = document.querySelector("input").value;
return val;
}
function calcPower(base, exponent){
var result = 1;
for(var counter=0; counter<exponent;counter++){
result*=base;
}
return result;
}
querySelector returns a reference to the first element of the given selector. See https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector. It is not the obvious way to fetch your values given that your function is set up to handle element ids.
Instead, individual elements with unique id can be referenced using document.getElementById("elementID") and you want the .value property of the element. See https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById.
To input values, the html needs some sort of input, you could use text or number inputs (both return strings, but the number input restricts entries to digits). The markup for these would be something like:
Number: <input type="number" id="inputValue"></input><br>
Exponent: <input type="number" id="inputExponent"></input>
Note the use of ids as attributes of the elements.
Javascript is a loosely typed language, meaning strict definition of variable types is not needed. This means that JS can make sensible calculations from 2*2 or "2"*"2" (both are calculated to be 4). However, it is good practice to formally convert string digits to numbers when you intend using them for calculations (not least because JS interprets "2"+"2" as "22" because + is both an arithmetic addition operator and a string concatenation operator so if you give it strings, JS assumes you want to concatenate them).
So, the fetchValue function could include the use of parseInt(string) to convert the input string values to numbers.
These principles are combined in the following working snippet to illustrate the approach:
function calcFunc(){
let num = fetchValue("inputValue");
let exponent = fetchValue("inputExponent");
console.log("The number " + num + " to the power of " + exponent + " is:");
console.log(calcPower(num, exponent));
}
function fetchValue(id){
return parseInt(document.getElementById(id).value);
}
function calcPower(base, exponent){
let result = 1;
for(let counter=0; counter<exponent;counter++){
result*=base;
}
return result;
}
input {
width: 3em;
}
Number: <input type="number" id="inputValue"></input><br>
Exponent: <input type="number" id="inputExponent"></input>
<p>
<button onclick="calcFunc()">process</button>
I hope this helps, If the exponent is negative, the result is 1 / (base^exponent). For example: 2^(-4) = 1 / (2^4) = 1 / 2 / 2 / 2 / 2. meaning the number 2 to the power of -4 is: 0.0625 and not 1
Math.abs is important here...
function fetchValue(id){
return document.getElementById(id).value;
}
function calcPower(base, exponent){
if (exponent == 0){
return 1;
}
else if(exponent < 0){
exponent = Math.abs(exponent);
return (1 / calcPower(base, exponent));
}
else if(exponent > 0){
return base * (calcPower(base,exponent - 1));
}
};
I have a factorial code but when it will find the result of the factorial it will get the result of the whole factorial.
Im looking for a code that finds the factorial of the last 5 factorials of a number? For example, 10! ? I need only the result of 10 x 9 x 8 x 7 x 6 = 30240? How do I do that?
<html>
<body>
<script type = "text/javascript">
var n = parseInt(window.prompt("Enter the Number:"));
var result = fact(n);
window.alert("Factorial of the given number " + result);
function fact(n)
{
if(n == 0)
return 1;
else
return (n*fact(n-1));
}
</script>
</body>
As MinusFour already noted: you want 10!/5!. You can do it that way and compute both values and divide. They divide exactly, no worry about fractions (proof omitted). But it is size-restricted, you cannot do e.g. 100!95! in JavaScript without a big-integer library and even with a big-integer library things like 1000000!/999998! will need a lot of computation time (both are numbers with over 5 million decimal digits).
My suggestion: no tricks, just compute it linearly like you would do it by hand:
function fact(n,k){
var t = 1;
for(var i = n;i>k;i--){
t *= i;
}
return t;
}
console.log(fact(10,5));
The first one must be the bigger one, both must be positive, all other checks and balances are omitted, too.
Using JS to run a simple formula, but like many JS calculations I've made before the decimal answers go on for way longer than I'd like and make it look sloppy.
Is there I way I can force the calculation to stop at a certain decimal place or force a round up from there?
Thanks!
<script>
var $u = $('input[name=u]');
var $a = $('input[name=a]');
var $h = $('input[name=h]');
$u.on('keyup',function() {
var u = +$u.val();
var a = +$a.val();
$h.val(u*4.605+a*1.308+28.003).toFixed(1);
});
$a.on('keyup',function() {
var u = +$u.val();
var a = +$a.val();
$h.val(u*4.605+a*1.308+28.003).toFixed(1);
});
</script>
I see you've tried toFixed(). I believe that is the solution, but you're trying to call it on a jQuery object. You should call it on the number before passing it into val().
Change your code to:
$a.on('keyup',function() {
var u = +$u.val();
var a = +$a.val();
$h.val((u*4.605+a*1.308+28.003).toFixed(1));
});
// $('#a').val(Math.PI).toFixed(1); // You're inserting the full value, and then executing
// toFixed on a jQuery Object. Not going to work.
$('#a').val( (Math.PI).toFixed(1) ); // How it should be written
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input id="a"/>
Math.floor(number)
Returns the next integer below given number.
Math.floor(1.66); // 1
Math.floor(-1.66); // -2
Math.ceil(number)
Returns the next integer above given number.
Math.ceil(1.66); // 2
Math.ceil(-1.66); // -1
Math.round(number)
Returns the nearest integer. Similar to Math.floor(number + 0.5);
Math.round(1.66); // 2
Math.round(-1.66); // -2
number|0 (or ~~number)
Discards the decimal portion of a number.
1.66|0; // 1
-1.66|0; // -1
number.toFixed(decimals)
Converts a number into a string with the specified number of decimals. Will either pad the result with zeroes or mathematically round to a certain number of decimals.
(1.66).toFixed(1); // "1.7"
(-1.66).toFixed(1); // "-1.7"
number.toFixed(decimals + 1).slice(0, -1)
Returns a fixed-decimal string, but chops the specified number of decimals without rounding.
(1.66).toFixed(2).slice(0, -1); // "1.6"
I have been using this function for calculating factorial numbers in JavaScript:
var f = [];
function factorial (n) {
if (n == 0 || n == 1)
return 1;
if (f[n] > 0)
return f[n];
return f[n] = factorial(n-1) * n;
}
All seemed to be going well until I tried the number 500. It returned infinity.
Is there a way that I can prevent infinity as an answer?
Thank you.
You indeed need to use bignumbers. With math.js you can do:
// configure math.js to work with enough precision to do our calculation
math.config({precision: 2000});
// evaluate the factorial using a bignumber value
var value = math.bignumber(500);
var result = math.factorial(value);
// output the results
console.log(math.format(result, {notation: 'fixed'}));
This will output:
1220136825991110068701238785423046926253574342803192842192413588385845373153881997605496447502203281863013616477148203584163378722078177200480785205159329285477907571939330603772960859086270429174547882424912726344305670173270769461062802310452644218878789465754777149863494367781037644274033827365397471386477878495438489595537537990423241061271326984327745715546309977202781014561081188373709531016356324432987029563896628911658974769572087926928871281780070265174507768410719624390394322536422605234945850129918571501248706961568141625359056693423813008856249246891564126775654481886506593847951775360894005745238940335798476363944905313062323749066445048824665075946735862074637925184200459369692981022263971952597190945217823331756934581508552332820762820023402626907898342451712006207714640979456116127629145951237229913340169552363850942885592018727433795173014586357570828355780158735432768888680120399882384702151467605445407663535984174430480128938313896881639487469658817504506926365338175055478128640000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
500! is, for lack of a better term, "[bleep]ing huge".
It is far, far beyond what can be stored in a double-precision float, which is what JavaScript uses for numbers.
There's no way to prevent this, other than use numbers that are reasonable :p
EDIT: To show you just how huge it is, here's the answer:
500! = 1220136825991110068701238785423046926253574342803192842192413588385845373153881997605496447502203281863013616477148203584163378722078177200480785205159329285477907571939330603772960859086270429174547882424912726344305670173270769461062802310452644218878789465754777149863494367781037644274033827365397471386477878495438489595537537990423241061271326984327745715546309977202781014561081188373709531016356324432987029563896628911658974769572087926928871281780070265174507768410719624390394322536422605234945850129918571501248706961568141625359056693423813008856249246891564126775654481886506593847951775360894005745238940335798476363944905313062323749066445048824665075946735862074637925184200459369692981022263971952597190945217823331756934581508552332820762820023402626907898342451712006207714640979456116127629145951237229913340169552363850942885592018727433795173014586357570828355780158735432768888680120399882384702151467605445407663535984174430480128938313896881639487469658817504506926365338175055478128640000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
That right there is a 1,135-digit number. For comparison, double-precision floats can handle about 15 digits of precision.
You could consider using an arbitrary precision numeric library. This is a question of its own, though. Here's one related question: https://stackoverflow.com/questions/744099/is-there-a-good-javascript-bigdecimal-library.
I dont know if anyone has solved this elsewise...
I'm a novice beginner in coding and dont know all the aspects. But after I faced this factorial problem myself, i came here when searching for the answer. I solved the 'infinity' display problem in another way. I dont know if its very efficient or not. But it does show the results of even verry high intergers.
Sorry for any redundancy or untidiness in the code.
<!DOCTYPE html>
<html>
<head>
<title>Factorial</title>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
</head>
<body>
<input type='text' id='number' />
<input type='button' value='!Factorial!' id='btn' />
<script>
var reslt=1;
var counter=0;
var mantissa=0; //stores the seperated matissa
var exponent=0; //stores the seperated exponent
$(document).ready(function (){
$('#btn').click(function (){
var num=parseFloat($('#number').val()); //number input by user
for(i=1;i<=num;i++){
reslt=reslt*i;
//when the result becomes so high that the exponent reaches 306, the number is divided by 1e300
if((parseFloat(reslt.toExponential().toString().split("e")[1]))>=300){
reslt=reslt/1e300; //the result becomes small again to be able to be iterated without becoming infinity
counter+=1; //the number of times that the number is divided in such manner is recorded by counter
}
}
//the mantissa of the final result is seperated first
mantissa=parseFloat(reslt.toExponential().toString().split("e")[0]);
//the exponent of the final result is obtained by adding the remaining exponent with the previously dropped exponents (1e300)
exponent=parseFloat(reslt.toExponential().toString().split("e")[1])+300*counter;
alert(mantissa+"e+"+exponent); //displays the result as a string by concatenating
//resets the variables and fields for the next input if any
$('#number').val('');
reslt=1;
mantissa=0;
exponent=0;
counter=0;
});
});
</script>
</body>
</html>
Javascript numbers can only get so big before they just become "Infinity". If you want to support bigger numbers, you'll have to use BigInt.
Examples:
// Without BigInt
console.log(100 ** 1000) // Infinity
// With BigInt
// (stackOverflow doesn't seem to print the result,
// unless I turn it into a string first)
console.log(String(100n ** 1000n)) // A really big number
So, for your specific bit of code, all you need to do is turn your numeric literals into BigInt literals, like this:
var f = [];
function factorial (n) {
if (n == 0n || n == 1n)
return 1n;
if (f[n] > 0n)
return f[n];
return f[n] = factorial(n-1n) * n;
}
console.log(String(factorial(500n)));
You'll find that you computer can run that piece of code in a snap.
Hi this is due to the nature of java script as it can't represents number above 253-1 reference so to solve this either wrap the number with BigInt(n) or add to the number >> 3n
const factorial = (n) => {
n = BigInt(n)
if ( n < 1 ) return 1n
return factorial(n - 1n) * n
}
I am using the following code snippet to calculate a total price. This works great except #totalPrice on some occasions expands out to for example $267.9999999999. How do I reformat #totalPrice within this function to just round to two decimals as is standard in dealing with price.
function getTotalCost(inventory) {
if(inventory) {
getTotalParts(inventory);
getTotalMarkup(inventory);
}
var labor = $('#labor').val() * 1;
var totals = 0;
for(i in totalMarkup) {
totals += totalMarkup[i];
}
totalCost = totals+labor;
/*if(totals == 0) {
totalCost = 0;
}*/
$('#totalPrice').html(totalCost);
}
You can have:
$('#totalPrice').html(totalCost.toFixed(2));
See:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number/toFixed
Notice that toFixed method returns a formatted number, therefore converts the number to a string. It's not a problem here because html wants a string, but it's keep it in mind that in order to avoid concatenation of string when you expects sum of numbers. I believe you use $('#labor').val() * 1; for this very reason. However it's not necessary, it's better use method like parseFloat or the unary plus operator:
var labor = +$('#labor').val();
When working with javascript the floating points are always a bad. Best you can do is, round it up.
But in this case you can do
(totalCost).toFixed(2);
You can use Math.round function in JavaScript like this.
totalCost = Math.round(totalCost*100)/100;
$('#totalPrice').html(totalCost);