I am trying to figure out a triangle excercise where the user inputs a number and the triangle is then created based on said number ex enter 5
This is what I want
**5
6 6
7 7 7
8 8 8 8
9 9 9 9 9
10 10 10 10 10**
Each line the number is increased by 1. I can't get my code to increase by 1.
I keep getting
5
5 5
5 5 5
5 5 5 5
5 5 5 5 5
Anyone have any suggestions? Thanks
let num = prompt("Enter a number");
//Check if its a number
num = parseInt(num);
//loop 1
for (i = 1; i <= 6; i++) {
//loop 2
for (y = 0; y < i; y++) {
document.write(num);
}
document.write(num = num +1; "<br>");
}
<p id="num"> </p>
You just have to use the entered number as the loop upper limit:
let num = prompt("Enter a number");
//Check if its a number
num = parseInt(num);
//loop 1
for (i = 1; i <= num; i++) {
//loop 2
for (y = 0; y < i; y++) {
document.write(num);
}
document.write("<br>");
}
This syntax is entirely invalid:
document.write(num = num +1; "<br>");
You're somehow confusing calling a function with defining a for loop. Those are two entirely different things.
Don't randomly try to munge together separate operations. Put each operation on its own line of code. The two operations you want to perform are:
Add 1 to num
Output a <br> element
These are separate operations. So separate them:
num = num +1;
document.write("<br>");
You don't seem to be placing the incrementation of your num before writing it to the document. See the code below check the line between loops.
let num = prompt("Enter a number");
//Check if its a number
num = parseInt(num);
//loop 1
for (let i = 1; i <= 6; i++) {
//loop 2
num++;
for (let y = 0; y < i; y++) {
document.write(num);
}
document.write("<br>");
}
<p id="num"> </p>;
Related
This question already has answers here:
What is the purpose of the var keyword and when should I use it (or omit it)?
(19 answers)
Does return stop a loop?
(7 answers)
Closed 12 months ago.
I'm a beginner in JavaScript and doing an online test to improve my skills. I came across to this question:
Add 1 point for each even number in the array
Add 3 points for each odd number in the array
Add 5 points every time the number 5 appears in the array
So if I am given this array as an example:
([1,2,3,4,5])
the output should be 13
This is what I have got so far:
export function find_total( my_numbers ) {
for(let i = 0; i < my_numbers.length; i++){
if(my_numbers[i] % 2 === 0) {
total = total + 1
}
if(my_numbers[i] % 2 === 1) {
total = total + 3
}
if(my_numbers[i] === 5) {
total = total + 5
}
return total
}
console.log(total)
}
But it is giving me errors. I get the logic in English but couldn't put it in JS.
What would be the right syntax here?
The problem is with your if statements.
function find_total( my_numbers ) {
let total = 0;
for(let i = 0; i < my_numbers.length; i++){
if(my_numbers[i] === 5) {
total = total + 5
}
else if(my_numbers[i] % 2 === 0) {
total = total + 1
}
else if(my_numbers[i] % 2 === 1) {
total = total + 3
}
}
return total;
}
console.log(find_total([1,2,3,4,5]))
This code should print the correct result of 13.
You were not getting an answer of 13 because 5 is odd so has 3 point and 5 point exclusive to 5. The key is not to treat 5 as having point of odd number but having it's own point irrespective of either it is odd or even.
There are following issues in your code:
total in the function find_total is never initialized
return statement is misplaced inside the for loop, it must be outside, signifying return value of the function find_total
Better to console.log the value of the function, instead of logging it inside. eg. console.log(find_total(...))
Fixing these, you will indeed get the return value as 16 for input [1, 2, 3, 4, 5] as pointed out in the comments.
function find_total(my_numbers) {
let total = 0 // Initialize total with a value of 0
for (let i = 0; i < my_numbers.length; i++) {
if (my_numbers[i] % 2 === 0) {
total = total + 1
}
if (my_numbers[i] % 2 === 1) {
total = total + 3
}
if (my_numbers[i] === 5) {
total = total + 5
}
}
return total // return outside the loop
}
console.log(find_total([1, 2, 3, 4, 5])) // console.log outside
Question : Given n, take the sum of the digits of n. If that value has
more than one digit, continue reducing in this way until a
single-digit number is produced. The input will be a non-negative
integer. Ex- 16 --> 1 + 6 = 7 942 --> 9 + 4 + 2 = 15 --> 1 +
5 = 6 132189 --> 1 + 3 + 2 + 1 + 8 + 9 = 24 --> 2 + 4 = 6 493193
--> 4 + 9 + 3 + 1 + 9 + 3 = 29 --> 2 + 9 = 11 --> 1 + 1 = 2
function digitalroot(n) {
let a = n;
var sum = 0;
while(a >= 1){
sum += a % 10;
a = Math.trunc(a/10)
}
if(sum > 9){
digitalroot(sum)
}
console.log("Print")
console.log(sum)
return sum
}
I tried above code but not getting correct output with below called input
With this two inputs passed in function: (16), (456)
O/P:
Print
7
Print
6
Print
15
Please help me, I am new to JavaScript
you forgot to return value from function call inside that sum>9 condition.
check recursion here : w3School
function digitalroot(n) {
let a = n;
var sum = 0;
while(a >= 1){
sum += a % 10;
a = Math.trunc(a/10)
}
if(sum > 9){
return digitalroot(sum)
}
return sum
}
console.log(digitalroot(493193));
Check this working example
function digitalroot(n){
console.log(`Value of n = ${n}`)
var digits = (""+n).split("");
for (var i = 0; i < digits.length; i++) {
digits[i] = +digits[i];
}
var finalVal = digits
let result = finalVal.reduce((a, b) => a + b, 0)
console.log(`Final Value with list ${result}`)
}
digitalroot(289)
The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832.
Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?
"use strict"
var data = "73167176531330624919225119674426574742355349194934\
96983520312774506326239578318016984801869478851843\
85861560789112949495459501737958331952853208805511\
12540698747158523863050715693290963295227443043557\
66896648950445244523161731856403098711121722383113\
62229893423380308135336276614282806444486645238749\
30358907296290491560440772390713810515859307960866\
70172427121883998797908792274921901699720888093776\
65727333001053367881220235421809751254540594752243\
52584907711670556013604839586446706324415722155397\
53697817977846174064955149290862569321978468622482\
83972241375657056057490261407972968652414535100474\
82166370484403199890008895243450658541227588666881\
16427171479924442928230863465674813919123162824586\
17866458359124566529476545682848912883142607690042\
24219022671055626321111109370544217506941658960408\
07198403850962455444362981230987879927244284909188\
84580156166097919133875499200524063689912560717606\
05886116467109405077541002256983155200055935729725\
71636269561882670428252483600823257530420752963450"
function largestMulitplication(ValueOfSequence) {
var Numbers, g = 1, ValueOfSequence, arr = [];
Numbers = data.split('');
for (var i = 0; i <= data.length; i++) {
if (i == ValueOfSequence) {
arr.push(g)
ValueOfSequence += 4
g = 1
}
g *= data[i];
}
return Math.max.apply(Math, arr);
}
alert(largestMulitplication(3));
When ValueOfSequence has value 3 and ValueOfSequence += 4 I get 5832 and that's correct. But if I change ValueOfSequence for 29 and ValueOfSequence += 30 I get incorrect answer. Anybody knows why?
I wrote a code with javascript for this problem :
"If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000."
but the result is false and i don't know why? can you help me guys
my code is :
function multipleSum(n){
var sum = 0;
for(var i = 1; i<n; i++){
var m3 = 3 * i;
var m5 = 5 * i;
if(m3 < n ){
sum=sum+m3
}
if(m5 < n ){
sum=sum+m5;
}
//if(m3 > n && m5 > n) {console.log(m3,m5,sum);break;}
}
return sum
}
console.log(multipleSum(1000)) //266333 but correct one is 233168 why?
Your logic is flawed. You should be iterating on each number (specified in range), and see if the modulus of the number with 3 or 5 is 0 or not. If modulus is zero, it means the number is divisible.
function multipleSum(n){
var sum = 0;
for(var i = 1; i<n; i++){
if(i % 3 == 0 || i % 5 ==0){ // gives reminder of 0, divisible by either 3 or 5
sum += i; // add in sum if that's the case.
}
}
return sum
}
console.log(multipleSum(1000))
Edit: tried some time understanding why you went with multiply approach, I think you are gathering factors and want to break out early from the loop instead of iterating on entire collection. This should help you:
function multipleSum(n){
var sum = 0;
for(var i = 1; i<n; i++){
var m3 = i * 3;
var m5 = i * 5;
if(m3 > n) break; // breaks early!!
if(m3 < n) sum += m3
if(m5 < n && m5 % 3 != 0) sum += m5; // make sure number is not divisible by 3, say m5 = 15, it will be captured as multiple of 3 anyway, we don't want duplicates.
}
return sum
}
console.log(multipleSum(1000))
Your logic is flawed in the way that, all the multiplications of 3 * 5 is doubled. Remember, you have:
3 * 1
5 * 1
3 * 2
3 * 3
5 * 2
3 * 4
3 * 5
5 * 3 // Here comes the dupe.
I would do this in a different way.
Get all the multiples of 3 in an array.
Get all the multiples of 5 in an array.
Break the loop when both the multiplications are greater than n.
Merge both the arrays.
Remove the duplicates.
Add everything using the .reduce() function.
var num = 1000;
var m3 = [];
var m5 = [];
for (i = 0; i < num; i++) {
if (i * 3 < num)
m3.push(i * 3);
if (i * 5 < num)
m5.push(i * 5);
if (i * 3 > num)
break;
}
m35 = m3.concat(m5);
m35u = m35.filter(function(item, pos) {
return m35.indexOf(item) == pos;
});
console.log(m35u.reduce((a, b) => a + b, 0));
I get 233168 as answer.
You can try this one liner (your home work: explain how this works ;):
console.log(
Array.from({length: 1000})
.reduce( (p, n, i) => p + (i % 3 === 0 || i % 5 === 0 ? i : 0), 0 )
);
Try this, maybe answer you.Thank
const solution = (numb) => {
const collectedNumb = [];
const maxDividing = parseInt(numb / 3);
for (let idx = 1; idx <= maxDividing; idx++) {
const multipled3 = idx * 3;
const multipled5 = idx * 5;
multipled3 < numb && collectedNumb.push(multipled3);
multipled5 < numb && collectedNumb.push(multipled5);
}
const uniqCollected = [...new Set(collectedNumb)].sort((a, b)=> a-b);
console.log(uniqCollected);
const reduced = uniqCollected.reduce((acc, numb) => acc + numb, 0);
return reduced;
};
I'm trying to add all the digits in an integer value until i get a value below 9 using Javascript.
for an example, if i have 198, I want to add these together like 1 + 9 + 8 = 18, and since 18 is higher than 9 add 1 +8 again = 9.
Rather than giving you full code I would just explain how to do it.
You can do modulo math by number%10 and subsequent int divide by 10 (number/10) until you get 0 to get all the digits of a number. Sum the individual digits and until sum > 9 repeat the above process in a loop.
Edit: okay here is the code for you:
<script>
var num=198;
n = num;
var sum;
do {
sum = 0;
while (n>0) {
rem = (n % 10);
sum += rem;
n = (n - rem)/10;
}
n = sum;
} while(sum>9);
alert("sum is: " + sum);
</script>
function foo(var x)
{
while(x > 9)
{
var y = 0;
while(x!=0)
{
y += x%10;
x = Math.floor(x/10);
}
x = y;
}
return x;
}
Here are two hints: (i % 10) gives the least significant decimal digit of i, while i /= 10 removes the least significant digit from i. The rest is left as an exercise for the reader.