So This makes it so every level from 1-30 will be 17 exp + 3 more after each level but i wanted to do the same thing but in Times (x) rather than adding 3 every level.
if (level > 30) {
var exp = 17;
level -= 30;
for (var i = 1; i <= level; i++) {
exp += 17 + (i * 3);```
var exp;
function Times(x) {
if (x > 30) {
exp = 17;
x-=30
for (var i = 1; i <= x; i++) {
exp += 17 + (i * 3);
}
}
return exp;
}
console.log(Times(45))
Related
I have a problem in JavaScript programing. I am beginner and from last 24 hrs I just completed one task that made pyramid star pattern which only work in console but the problem is this, that the same coding doesn't work on browser. In the browser the triangle become 📐 such type of triangle.
I added br to code for the browser but the triangle become 📐 right angle triangle.
use pre tag to render your result, so it doesn't remove extra spaces. most html tag will remove extra spaces because it thinks those are useless.
let starCount = 1;
const row = 35
let result = "";
for (let i = 0; i < row; i++) {
let starString = "";
const p = starCount;
for (let j = 0; j < row; j++) {
if (j >= ((row - p) / 2) && j < (((row - p) / 2) + p)) {
starString += "*";
continue;
}
starString += " "
}
result += starString + "\n";
if (row % 2 == 0) {
if (i < (row / 2) - 1) {
starCount += 2;
}
if (i > ((row / 2) - 1)) {
starCount -= 2;
}
} else {
if (i < Math.floor(row / 2)) {
starCount += 2;
} else {
starCount -= 2;
}
}
}
document.querySelector("pre").innerHTML = result;
<pre></pre>
I am currently trying to solve the xmas tree problem, with internal tree-like shape.
issue is with internal spacing, it supposed to be like: 1, 5, 7, 9. Instead it is 1, 3, 4, 5. I do not know, how to increment s loop by 2 in each loop turn.
/*
*********
**** ****
*** ***
** **
* *
*********
*/
function drawTree(h) {
let n = h + 3;
for (var i = 1; i <= 1; i++) {
var temp = "";
for (var j = 1; j <= n; j++) {
temp = temp + "*";
}
console.log(temp);
}
for (var i = 0; i < h - 2; i++) {
var tree = '';
console.log("\n");
for (var k = 3; k <= h - i; k++) {
tree += "*";
};
tree += "s";
for (var k = 1; k <= i; k++) {
for (var k = 1; k <= i; k++) {
tree += "s";
};
tree += "s";
};
for (var k = 3; k <= h - i; k++) {
tree += "*";
};
console.log(tree);
};
console.log("\n");
let g = h + 3;
for (var i = 1; i <= 1; i++) {
var temp = "";
for (var j = 1; j <= g; j++) {
temp = temp + "*";
}
console.log(temp);
}
};
drawTree(6);
function drawTree(stars, rowLength) {
for (let row = 0; row < rowLength; row++) {
if (row === 0) {
console.log("*".repeat(stars));
} else if(row === rowLength - 1) {
console.log("*".repeat(stars));
} else {
let spaces = 2 * row - 1;
if (spaces > stars) {
spaces = stars;
}
let numStarsInRow = "*".repeat((stars - spaces) / 2);
console.log(numStarsInRow + " ".repeat(spaces) + numStarsInRow);
}
}
}
drawTree(9, 5)
You can implement this by nesting loops over the height and the width of the tree, noting that the output is a * whenever:
it's the first or last row; or
the current x position is less than or equal to the halfway point minus the row number; or
the current x position is greater than or equal to the halfway point plus the row number
For all other cases the output is a space. For example:
function drawTree(height) {
// compute the width of the tree from the height
let width = height % 2 ? height + 2 : height + 3;
// find the halfway point
let half = (width - 1) / 2;
for (let i = 0; i < height; i++) {
let l = '';
for (let j = 0; j < width; j++) {
if (i == 0 || // first row
i == height - 1 || // last row
j <= (half - i) || // left side
j >= (half + i) // right side
) {
l += '*';
}
else {
l += ' ';
}
}
console.log(l);
}
}
drawTree(6);
drawTree(5);
This is my code
function convertToCurr(value) {
var x = value.toString().length;
var z = x % 3;
var a = 0;
if (z == 0) {
a = (x / 3) - 1;
}
else {
a = (x / 3);
}
var last = 0;
var vals = [];
var i;
for (i = 1; i <= a; i++) {
steps = 3;
start = x - steps * i;
end = start + steps;
last = end - steps;
vals.unshift(value.toString().slice(start, end));
}
vals.unshift("R " + value.toString().slice(0, last));
return vals.join();
}
basicIO.write(convertToCurr(input));
context.log.INFO("log data");
}
These are my outputs
{"output":"R 1,000,000,.00","log":["log data"]}
{"output":"R 1,000,.00","log":["log data"]}
I need to exctract the last "," so that the amounts make sense
The most straightforward solution is to perform a String.prototype.replace() on the final join().
function convertToCurr(value) {
var x = value.toString().length;
var z = x % 3;
var a = 0;
if (z == 0) {
a = (x / 3) - 1;
}
else {
a = (x / 3);
}
var last = 0;
var vals = [];
var i;
for (i = 1; i <= a; i++) {
steps = 3;
start = x - steps * i;
end = start + steps;
last = end - steps;
vals.unshift(value.toString().slice(start, end));
}
vals.unshift("R " + value.toString().slice(0, last));
return vals.join().replace(',.', '.');
}
console.log(convertToCurr(10000.75));
console.log(convertToCurr(10.01));
console.log(convertToCurr(1000));
console.log(convertToCurr(7002344));
It should be noted that replace() only replaces a single instance of the substring you provide it in the input string, but this doesn't matter here since ,. only appears in your output string one time.
function convertToCurr(value) {
var x = value.toString().length;
var z = x % 3;
var a = 0;
var combinedString; // holds string value after join
if (z == 0) {
a = x / 3 - 1;
} else {
a = x / 3;
}
var last = 0;
var vals = [];
var i;
for (i = 1; i <= a; i++) {
steps = 3;
start = x - steps * i;
end = start + steps;
last = end - steps;
vals.unshift(value.toString().slice(start, end));
}
vals.unshift("R " + value.toString().slice(0, last));
combinedString = vals.join(); // join array into string
return combinedString.replace(",.", "."); // replace ,. with .
}
console.log(convertToCurr(50000000.15));
My results for numbers between 1 and 28321 (limit)
sum of all numbers: 395465626
sum of all abundant numbers: 392188885
sum of all non abundant numbers: 3276741 (correct answer is 4179871)
var divisors = function(number){
sqrtNumber = Math.sqrt(number);
var sum = 1;
for(var i = 2; i<= sqrtNumber; i++)
{
if (number == sqrtNumber * sqrtNumber)
{
sum += sqrtNumber;
sqrtNumber--;
}
if( number % i == 0 )
{
sum += i + (number/i);
}
}
if (sum > number) {return true;}
else {return false;}
};
var abundent = [], k = 0;
var upperLimit = 28123;
for (var i = 1; i <= upperLimit; i++)
{
if (divisors(i))
{abundent[k] = i; k++};
}
var abundentCount = abundent.length;
var canBeWrittenAsAbundant = [];
for (var i = 0; i < abundentCount; i++){
for (var j = i; j < abundentCount; j++){
if (abundent[i] + abundent[j] <= upperLimit){canBeWrittenAsAbundant[abundent[i]+abundent[j]] = true;}
else {
break;
}
}
}
for (i=1; i <= upperLimit; i++){
if (canBeWrittenAsAbundant[i] == true){continue;}
else {canBeWrittenAsAbundant[i] = false;}
}
var sum = 0;
for (i=1; i <= upperLimit; i++)
{
if (!canBeWrittenAsAbundant[i]){
sum += i;
}
}
console.log(sum);
I'm using http://www.mathblog.dk/project-euler-23-find-positive-integers-not-sum-of-abundant-numbers/ as guidance, but my results are different. I'm a pretty big newb in the programming community so please keep that in mind.
You do not need to calculate the sum of all numbers using a cycle, since there is a formula, like this:
1 + 2 + ... + number = (number * (number + 1)) / 2
Next, let's take a look at divisors:
var divisors = function(number){
sqrtNumber = Math.sqrt(number);
var sum = 1;
for(var i = 2; i<= sqrtNumber; i++)
{
if (number == sqrtNumber * sqrtNumber)
{
sum += sqrtNumber;
sqrtNumber--;
}
if( number % i == 0 )
{
sum += i + (number/i);
}
}
if (sum > number) {return true;}
else {return false;}
};
You initialize sum with 1, since it is a divisor. However, I do not quite understand why do you iterate until the square root instead of the half of the number. For example, if you call the function for 100, then you are iterating until i reaches 10. However, 100 is divisible with 20 for example. Aside of that, your function is not optimal. You should return true as soon as you found out that the number is abundant. Also, the name of divisors is misleading, you should name your function with a more significant name, like isAbundant. Finally, I do not understand why do you decrease square root if number happens to be its exact square and if you do so, why do you have this check in the cycle. Implementation:
var isAbundant = function(number) {
var sum = 1;
var half = number / 2;
for (var i = 2; i <= half; i++) {
if (number % i === 0) {
sum += i;
if (sum > number) {
return true;
}
}
}
return false;
}
Note, that perfect numbers are not considered to be abundant by the function.
You do not need to store all numbers, since you are calculating aggregate data. Instead, do it like this:
//we assume that number has been initialized
console.log("Sum of all numbers: " + ((number * (number + 1)) / 2));
var abundantSum = 0;
var nonAbundantSum = 0;
for (var i = 0; i <= number) {
if (isAbundant(i)) {
abundantSum += i;
} else {
nonAbundantSum += i;
}
}
console.log("Sum of non abundant numbers: " + nonAbundantSum);
console.log("Sum of abundant numbers: " + abundantSum);
Code is not tested. Also, beware overflow problems and structure your code.
Below is the Corrected Code for NodeJS..
var divisors = function (number) {
sqrtNumber = Math.sqrt(number);
var sum = 1;
var half = number / 2;
for (var i = 2; i <= half; i++) {
if (number % i === 0) { sum += i; }
}
if (sum > number) { return true; }
else { return false; }
};
var abundent = [], k = 0;
var upperLimit = 28123;
for (var i = 1; i <= upperLimit; i++) {
if (divisors(i)) { abundent[k] = i; k++ };
}
var abundentCount = abundent.length;
var canBeWrittenAsAbundant = [];
for (var i = 0; i < abundentCount; i++) {
for (var j = i; j < abundentCount; j++) {
if (abundent[i] + abundent[j] <= upperLimit) { canBeWrittenAsAbundant[abundent[i] + abundent[j]] = true; }
else {
break;
}
}
}
for (i = 1; i <= upperLimit; i++) {
if (canBeWrittenAsAbundant[i] == true) { continue; }
else { canBeWrittenAsAbundant[i] = false; }
}
var sum = 0;
for (i = 1; i <= upperLimit; i++) {
if (!canBeWrittenAsAbundant[i]) {
sum += i;
}
}
console.log(sum);
Is there a way to calculate pi in Javascript? I know there you can use Math.PI to find pie like this:
var pie = Math.PI;
alert(pie); // output "3.141592653589793"
but this is not accurate. What I want is to be able to calculate it, to have as many digits as you want, not anything like pie = 3.141592.... But still, what I want is not have just have some more digits, but as much as you can (like having one thousand digits, but I need more).
Here is an implementation of a streaming algorithm described by Jeremy Gibbons in Unbounded Spigot Algorithms for the Digits of Pi (2004), Chaper 6:
function * generateDigitsOfPi() {
let q = 1n;
let r = 180n;
let t = 60n;
let i = 2n;
while (true) {
let digit = ((i * 27n - 12n) * q + r * 5n) / (t * 5n);
yield Number(digit);
let u = i * 3n;
u = (u + 1n) * 3n * (u + 2n);
r = u * 10n * (q * (i * 5n - 2n) + r - t * digit);
q *= 10n * i * (i++ * 2n - 1n);
t *= u;
}
}
// Demo
let iter = generateDigitsOfPi();
let output = document.querySelector("div");
(function displayTenNextDigits() {
let digits = "";
for (let i = 0; i < 10; i++) digits += iter.next().value;
output.insertAdjacentHTML("beforeend", digits);
scrollTo(0, document.body.scrollHeight);
requestAnimationFrame(displayTenNextDigits);
})();
div { word-wrap:break-word; font-family: monospace }
<div></div>
I found this code on this website:
mess = "";
Base = Math.pow(10, 11);
cellSize = Math.floor(Math.log(Base) / Math.LN10);
a = Number.MAX_VALUE;
MaxDiv = Math.floor(Math.sqrt(a));
function makeArray(n, aX, Integer) {
var i = 0;
for (i = 1; i < n; i++) aX[i] = null;
aX[0] = Integer
}
function isEmpty(aX) {
var empty = true
for (i = 0; i < aX.length; i++)
if (aX[i]) {
empty = false;
break
}
return empty
}
function Add(n, aX, aY) {
carry = 0
for (i = n - 1; i >= 0; i--) {
aX[i] += Number(aY[i]) + Number(carry);
if (aX[i] < Base) carry = 0;
else {
carry = 1;
aX[i] = Number(aX[i]) - Number(Base)
}
}
}
function Sub(n, aX, aY) {
for (i = n - 1; i >= 0; i--) {
aX[i] -= aY[i];
if (aX[i] < 0) {
if (i > 0) {
aX[i] += Base;
aX[i - 1]--
}
}
}
}
function Mul(n, aX, iMult) {
carry = 0;
for (i = n - 1; i >= 0; i--) {
prod = (aX[i]) * iMult;
prod += carry;
if (prod >= Base) {
carry = Math.floor(prod / Base);
prod -= (carry * Base)
} else carry = 0;
aX[i] = prod
}
}
function Div(n, aX, iDiv, aY) {
carry = 0;
for (i = 0; i < n; i++) {
currVal = Number(aX[i]) + Number(carry * Base);
theDiv = Math.floor(currVal / iDiv);
carry = currVal - theDiv * iDiv;
aY[i] = theDiv
}
}
function arctan(iAng, n, aX) {
iAng_squared = iAng * iAng;
k = 3;
sign = 0;
makeArray(n, aX, 0);
makeArray(n, aAngle, 1);
Div(n, aAngle, iAng, aAngle);
Add(n, aX, aAngle);
while (!isEmpty(aAngle)) {
Div(n, aAngle, iAng_squared, aAngle);
Div(n, aAngle, k, aDivK);
if (sign) Add(n, aX, aDivK);
else Sub(n, aX, aDivK);
k += 2;
sign = 1 - sign
}
mess += "aArctan=" + aArctan + "<br>"
}
function calcPI(numDec) {
var ans = "";
t1 = new Date();
numDec = Number(numDec) + 5;
iAng = new Array(10);
coeff = new Array(10);
arrayLength = Math.ceil(1 + numDec / cellSize);
aPI = new Array(arrayLength);
aArctan = new Array(arrayLength);
aAngle = new Array(arrayLength);
aDivK = new Array(arrayLength);
coeff[0] = 4;
coeff[1] = -1;
coeff[2] = 0;
iAng[0] = 5;
iAng[1] = 239;
iAng[2] = 0;
makeArray(arrayLength, aPI, 0);
makeArray(arrayLength, aAngle, 0);
makeArray(arrayLength, aDivK, 0);
for (var i = 0; coeff[i] != 0; i++) {
arctan(iAng[i], arrayLength, aArctan);
Mul(arrayLength, aArctan, Math.abs(coeff[i]));
if (coeff[i] > 0) Add(arrayLength, aPI, aArctan);
else Sub(arrayLength, aPI, aArctan)
}
Mul(arrayLength, aPI, 4);
sPI = "";
tempPI = "";
for (i = 0; i < aPI.length; i++) {
aPI[i] = String(aPI[i]);
if (aPI[i].length < cellSize && i != 0) {
while (aPI[i].length < cellSize) aPI[i] = "0" + aPI[i]
}
tempPI += aPI[i]
}
for (i = 0; i <= numDec; i++) {
if (i == 0) sPI += tempPI.charAt(i) + ".<br>";
else {
if (document.getElementById("cbCount").checked) addcount = " (" + (i) + ")";
else addcount = "";
if (document.getElementById("cbSpace").checked) thespace = " ";
else thespace = "";
if ((i) % 50 == 0 && i != 0) sPI += tempPI.charAt(i) + addcount + "<br>";
else if (i % 5 == 0) sPI += tempPI.charAt(i) + thespace;
else sPI += tempPI.charAt(i)
}
}
ans += ("PI (" + numDec + ")=" + sPI + "<br>");
ans += ("Win PI=<br>3.1415926535897932384626433832795<br>");
t2 = new Date();
timeTaken = (t2.getTime() - t1.getTime()) / 1000;
ans += "It took: " + timeTaken + " seconds";
var myDiv = document.getElementById("d1");
myDiv.innerHTML = ans
}
<form name="" onsubmit="calcPI(this.t1.value);return false;">
Number of Digits:<br>
<input type="text" name="t1" id="t1" value="100" size="25" maxlength="25">
<br>Add Count:
<input type="checkbox" name="cbCount" id="cbCount" value="" checked="checked">
<br>Add Spaces:
<input type="checkbox" name="cbSpace" id="cbSpace" value="" checked="checked">
<br>
<input type="button" value="Calculate Pi" onclick="calcPI(this.form.t1.value)">
</form>
<div id="d1"></div>
You can approximate the value of π through the use of Monte Carlo simulation. Generate a random X and Y each in the range [-1,1] Then the likelihood (X, Y) is in the unit circle centered at the origin is π/4. More samples yields a better estimate of its value. You can then estimate π by comparing the ratio of samples in the unit circle with the total number of samples and multiply by 4.
this.pi = function(count) {
var inside = 0;
for (var i = 0; i < count; i++) {
var x = random()*2-1;
var y = random()*2-1;
if ((x*x + y*y) < 1) {
inside++
}
}
return 4.0 * inside / count;
}
Here is my implementation using Infinite Series
function calculatePI(iterations = 10000){
let pi = 0;
let iterator = sequence();
for(let i = 0; i < iterations; i++){
pi += 4 / iterator.next().value;
pi -= 4 / iterator.next().value;
}
function* sequence() {
let i = 1;
while(true){
yield i;
i += 2;
}
}
return pi;
}
You can use this for your purpose
Math.PI.toFixed(n)
where n is the number of decimals you wish to display.
It displays the rounded value of pi. It can be considered fairly correct upto 15 decimal places.