JavaScript - Right Pascal pattern with the Fibonacci sequence - javascript

I'm trying to create a Pascal triangle using the Fibonacci sequence. I´m looking for this output:
0
0 1
0 1 1
0 1 1 2
0 1 1 2 3
0 1 1 2 3 5
0 1 1 2 3 5 8
0 1 1 2 3 5
0 1 1 2 3
0 1 1 2
0 1 1
0 1
0
This is the code I have written so far. I managed to get the Fibonacci sequence running into a triangle but not the way I want.
function fiboP(n) {
let string = "";
let n1 = 0
let n2 = 1
for (let i = 1; i <= n; i++) {
for (let j = 0; j < i; j++) {
string += n1 + " ";
next_num = n1 + n2;
n1 = n2;
n2 = next_num;
}
string += "\n";
}
for (let i = 1; i <= n - 1; i++) {
for (let j = 0; j < n - i; j++) {
string += n1 + " ";
next_num = n2 - n1;
n2 = n1;
n1 = next_num;
}
string += "\n";
}
console.log(string)
}
fiboP(5)
Output:
0
1 1
2 3 5
8 13 21 34
55 89 144 233 377
610 377 233 144
89 55 34
21 13
8
I would like to understand what I am missing here and if there is a cleaner and simpler way to produce the desired output.

If you reset your values when you go to next line, you should be able to generate the output you're looking for
function fiboP(n) {
let string = "";
for (let i = 1; i <= n; i++) {
let n1 = 0
let n2 = 1
for (let j = 0; j < i; j++) {
string += n1 + " ";
next_num = n1 + n2;
n1 = n2;
n2 = next_num;
}
string += "\n";
}
for (let i = 1; i <= n - 1; i++) {
let n1 = 0
let n2 = 1
for (let j = 0; j < n - i; j++) {
string += n1 + " ";
next_num = n2 + n1;
n2 = n1;
n1 = next_num;
}
string += "\n";
}
console.log(string)
}
fiboP(7)
As an improvement i will suggest finding fibonacci sequence once and then just using these values to create this triangle.

Related

Having bugs in digPow function even I have tested it alot from codewars

Hello I want to ask what's wrong with my solution when I am gonna test the solution it appears that expected -1 to equal 12933
The whole instructions are from codewors
The Question:
Some numbers have funny properties. For example:
89 --> 8¹ + 9² = 89 * 1
695 --> 6² + 9³ + 5⁴= 1390 = 695 * 2
46288 --> 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51
Given a positive integer n written as abcd... (a, b, c, d... being digits) and a positive integer p
we want to find a positive integer k, if it exists, such that the sum of the digits of n taken to the successive powers of p is equal to k * n.
In other words:
Is there an integer k such as : (a ^ p + b ^ (p+1) + c ^(p+2) + d ^ (p+3) + ...) = n * k
If it is the case we will return k, if not return -1.
Note: n and p will always be given as strictly positive integers.
digPow(89, 1) should return 1 since 8¹ + 9² = 89 = 89 * 1
digPow(92, 1) should return -1 since there is no k such as 9¹ + 2² equals 92 * k
digPow(695, 2) should return 2 since 6² + 9³ + 5⁴= 1390 = 695 * 2
digPow(46288, 3) should return 51 since 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51
My Solution:
function digPow(p, n) {
let arrayP = [...String(p)].map((e) => Number(e));
let arrayPLength = arrayP.length;
let nums = [];
let firstResult = [];
for (let i = n; i < 5000; i++) {
nums.push(i);
}
for (let i = n; i < nums.length; i++) {
let currentPow = [];
let j = i;
let k = i + arrayPLength;
while (j < k) {
currentPow.push(j);
j++;
if (j == k) break;
}
let result = 0;
for (let h = 0; h < arrayP.length; h++) {
result = arrayP[h] ** currentPow[h] + result;
}
firstResult.push(result);
}
for (let i = 0; i < firstResult.length; i++) {
for (let j = 0; j < 100; j++) {
if (firstResult[i] == p * j) return j;
}
}
return -1;
}

Javascript multiplying strings

I was doing following leetcode question on multiplying
Given two non-negative integers num1 and num2 represented as strings, return the
product of num1 and num2, also represented as a string.
Note: You must not use any built-in BigInteger library or convert the inputs to
integer directly.
Example 1:
Input: num1 = "2", num2 = "3"
Output: "6"
Example 2:
Input: num1 = "123", num2 = "456"
Output: "56088"
Constraints:
- 1 <= num1.length, num2.length <= 200
- num1 and num2 consist of digits only.
- Both num1 and num2 do not contain any leading zero, except the number 0 itself.
For this used the following approach
Convert the string to int
Multiply the int
Algo for the same is
const numberMap = {
"0": 0,
"1": 1,
"2": 2,
"3": 3,
"4": 4,
"5": 5,
"6": 6,
"7": 7,
"8": 8,
"9": 9
}
var multiply = function(num1, num2) {
let i = num1.length
let j = num2.length
let sum = currentPower = 0
let firstNumber = secondNumber = 0
while(i > 0 || j > 0) {
// if I or J is equal to zero, means we have itterated hence we will set the value to one
const firstNum = i > 0 ? (numberMap[num1[i-1]]) * (10**currentPower) : 0
const secondNum = j > 0 ? (numberMap[num2[j-1]]) * (10**currentPower) : 0
firstNumber += firstNum
secondNumber += secondNum
currentPower++
i--
j--
}
sum = firstNumber * secondNumber
return sum.toString()
};
but when the following input is given
"123456789"
"987654321"
it yields the following output "121932631112635260" instead of "121932631112635269"
Any idea how I can fix this?
You could multiply each digit with each other digit and take the indices as position.
Like you would do by hand, like
1 2 3 4 * 4 3 2 1
-------------------------
1 2 3 4
1 4 6 8
3 6 9 12
4 8 12 16
-------------------------
5 3 2 2 1 1 4
This approach uses the reversed arrays of the strings and reverse the result set as well.
Before retuning the result, the array is filterd by the leading zeros.
function multiply(a, b) {
var aa = [...a].reverse(),
bb = [...b].reverse(),
p = [],
i, j;
for (i = 0; i < aa.length; i++) {
for (j = 0; j < bb.length; j++) {
if (!p[i + j]) p[i + j] = 0;
p[i + j] += aa[i] * bb[j];
if (p[i + j] > 9) {
if (!p[i + j + 1]) p[i + j + 1] = 0;
p[i + j + 1] += Math.floor(p[i + j] / 10);
p[i + j] %= 10;
}
}
}
return p
.reverse()
.filter((valid => (v, i, { length }) => valid = +v || valid || i + 1 === length)(false))
.join('');
}
console.log(multiply('2', '3')); // 6
console.log(multiply('123', '456')); // 56088
console.log(multiply('9133', '0')); // 0
console.log(multiply('9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999', '9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999'));
function multiply() {
var str = document.getElementById('a').value;
var str1 = document.getElementById('b').value;
var l = str.length;
var l1 = str1.length;
var list = [];
var prod = 0;
var cur = 0;
list.length = l + l1;
// store 0 to to all list elements
list.fill(0);
// access string in reverse
for (var i = l - 1; i >= 0; i--) {
for (
var j = l1 - 1;
j >= 0;
j-- // access string in reverse
) {
// ASCII value of character and - ("0") ASCII Value 48
prod = (str.charCodeAt(i) - 48) * (str1.charCodeAt(j) - 48);
cur = list[i + j + 1] + prod;
list[i + j + 1] = cur % 10;
list[i + j] += parseInt(cur / 10);
}
}
var res = '';
res = list.join('');
if (res[0] == 0) {
// if First Char ==0 then remove
res = res.slice(1);
}
console.log(res);
}
var multiply = function(num1, num2) {
let v1=BigInt(num1)
let v2=BigInt(num2)
let v3=v1*v2
return v3.toString()
};
Just convert to Numbers, multiply, and then convert back to a string.
function mult(a, b){
return (Number(a) * Number(b)).toString();
}
In JavaScript, ints are not a specific type. They're the number type. We could use the parseInt() function instead of the Number() function to convert, but we know we're receiving an int as an input anyway, so there's no need for that kind of parsing.

find sum of multiples 3 and 5, JS

I'm given a number and I need to find the sum of the multiples of 3 and 5 below the number.
For example:
20 => 78 = 3 + 5 + 6 + 9 + 10 + 12 + 15 + 18
My code works, but not for numbers greater than 1,000,000 (I tested it for 100,000 - it gives the result with 2sec delay). So, it should be optimized. Could someone help me? Why is my code slow? Thanks.
My logic is as follows:
add multiples to an array
filter duplicate values
sum all values
my code:
function sumOfMultiples(number) {
let numberBelow = number - 1;
let numberOfThrees = Math.floor(numberBelow / 3);
let numberOfFives = Math.floor(numberBelow / 5);
let multiples = [];
let multipleOfThree = 0;
let multipleOfFive = 0;
for (var i = 0; i < numberOfThrees; i++) {
multiples.push(multipleOfThree += 3);
}
for (var j = 0; j < numberOfFives; j++) {
multiples.push(multipleOfFive += 5);
}
return multiples
.filter((item, index) => multiples.indexOf(item) === index)
.reduce((a, b) => a + b);
}
You can also do this without using any loops.
For example if N is 1000, the sum of all multiples of 3 under 1000 is 3 + 6 + 9 ..... 999 => 3( 1 + 2 + 3 .... 333)
Similarly for 5, sum is 5(1 + 2 + 3 .... 200). But we have to subtract common multiples like 15, 30, 45 (multiples of 15)
And sum of first N natural numbers is N*(N+1)/2;
Putting all of this together
// Returns sum of first N natural numbers
const sumN = N => N*(N+1)/2;
// Returns number of multiples of a below N
const noOfMulitples = (N, a) => Math.floor((N-1)/a);
function sumOfMulitples(N) {
const n3 = noOfMulitples(N, 3); // Number of multiples of 3 under N
const n5 = noOfMulitples(N, 5); // Number of multiples of 5 under N
const n15 = noOfMulitples(N, 15); // Number of multiples of 3 & 5 under N
return 3*sumN(n3) + 5*sumN(n5) - 15*sumN(n15);
}
You can just run a loop from 1 to number, and use the modulo operator % to check if i divides 3 or 5:
function sumOfMultiples(number) {
var result = 0;
for (var i = 0; i < number; i++) {
if (i % 5 == 0 || i % 3 == 0) {
result += i;
}
}
return result;
}
console.log(sumOfMultiples(1000));
console.log(sumOfMultiples(100000));
console.log(sumOfMultiples(10000000));
You can do that just using a single loop.
function sumOfMultiples(number) {
let sum = 0;
for(let i = 1; i < number; i++){
if(i % 3 === 0 || i % 5 === 0){
sum += i;
}
}
return sum;
}
console.time('t');
console.log(sumOfMultiples(100000))
console.timeEnd('t')
You can do something like this
Set the difference equal to 5 - 3
Start loop with current as 0, keep looping until current is less than number,
Add 3 to current in every iteration,
Add difference to current and check if it is divisible by 5 only and less than number, than add it final result,
Add current to final result
function sumOfMultiples(number) {
let num = 0;
let difference = 5 - 3
let current = 0
while(current < number){
current += 3
let temp = current + difference
if((temp % 5 === 0) && (temp %3 !== 0) && temp < number ){
num += temp
}
difference += 2
if(current < number){
num += current
}
}
return num
}
console.log(sumOfMultiples(20))
console.log(sumOfMultiples(1000));
console.log(sumOfMultiples(100000));
console.log(sumOfMultiples(10000000));
you can do something like this
function multiplesOfFiveAndThree(){
let sum = 0;
for(let i = 1; i < 1000; i++) {
if (i % 3 === 0 || i % 5 === 0) sum += i;
}
return sum;
}
console.log(multiplesOfFiveAndThree());

How to console.log number in the following format?

I'm trying to display numbers in the following format can you please tell me what is wrong?
Can not use div. As i'm printing this in the console.
I for n = 5:
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1
I have tried the following code:
n = 10
for (var i = 1; i <= n; i++) {
for (var j = 1; j <= i; j++) {
console.log("0" + j + " ");
}
console.log("<br />");
}
n = 10
for (var i = 1; i <= n; i++) {
for (var j = 1; j <= i; j++) {
console.log("0" + j + " ");
}
console.log("<br />");
}
But it displays something like this:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10
Here is the code for your Task. It takes numbers from 1 to declared. Also puts some space at the beginning of each row. You need to declare a string at the beginning of each row and then add all elements to it. When all loops are done, you can print it in console with console.log.
var n = 10 // Declaring number of rows
for (var i = 1; i <= n; i++) {
var row = ''; //declaring text variable for current row
for (var x = n - i; x >= 1; x--) {
row += ' '; //adding spaces in begining of the row
}
for (var j = 1; j <= i; j++) {
row += ' ' + j; // numbers which increase up to middle
}
for (var k = i - 1; k >= 1; k--) {
row += ' ' + k; // adding rest of the numbers to the row
}
console.log(row); //displaying whole row
}
for the algorithm point of view you have the forward loop but you missed the downward loop
adding it more the indentation from your first version of the question :
var n = 10
for (var i = 1; i <= n; i++) {
for (var j = 0; j < n - i; j++) {
document.write(" ");
}
for (var j = 1; j <= i; j++) {
document.write(" " + j + " ");
}
for (var j = i - 1; j >= 1; j--) {
document.write(" " + j + " ");
}
document.write("<br />");
}
P.S. It is the very first time I write code in javascript ;-)

JavaScript nested for loops to display numbers without HTML

I need to display a number range between 1 and 30 in the console, but in a specific way. While I've figured out how to get the range using a for loop, I have not figured out how to display the numbers in the console like in the image shown below where each * represents a number 1-30. I need numbers 1-30 to be displayed 7 rows across, and 5 rows down, without using HTML tables.
example
My code, to display the number range, is as follows:
for (var i = 1; i <= 5; i++)
{
var output = " ";
for (var j = 0; j <= 7; j += 1)
{
output += "*" + "\t";
}
console.log(output);
}
So far I have tried adding a third nested for loop, but there will be 5 iterations of 1 - 30 displayed 7 times. I have also tried using an array of 1-30, a while loop, an if statement, and have tried adding or multiplying variables with similar results.
I can't help but feel like I am approaching this the wrong way. I am considering using an array and having the inner for loop display each index of the array, but I am not sure if JavaScript has the ability to move to the next index after printing the previous index (1 then 2 then 3, etc) in the way in which I need it to as shown in the image.
This code works
var output="";var count = 0;
for (var i = 1; i <= 5; i++)
{
//output = " ";
for (var j = 0; j < 7; j += 1)
{
output +=(count+1)+"\t";count ++;
}output+="\n";
//document.write(output);
}
console.log(output);
Output:
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35
Problem in Question:
Question States -Number range between 1 and 30 in the console but specified order of
matrix is 7*5 which is equal to 35 not 30 which was wrongly mentioned
in the questiion.
Screenshot
As indicated by #torazaburo the OP is looking to populate numbers as opposed to [ * ] . Though SaiKiranUppu had a satisfactory answer and should be awarded the upvote, I wanted to offer another solution:
JS:
function matrix(r, c) {
var n = '';
var x = 1;
for(var i = 1; i <= r; i++) {
for(var j = 0; j < c; j++) {
n += x + '\t';
x++;
}
n += '\n';
}
console.log(n);
};
matrix(5, 7);
You can just do this. I do it only for your..
var lastJ = 1;
for (var i = 1; i <= 6; i++) {
var output = " ";
var j = lastJ ;
var totalLoop = j+4;
for (j = lastJ; j <= totalLoop; j++) {
output += j + "\t";
}
console.log(output);
lastJ = j;
}
output is like this
console output in image
If you want calendar like output use this
var lastJ = 1;
for (var i = 1; i <= 5; i++) {
var output = " ";
var j = lastJ ;
var totalLoop = j+6;
for (j = lastJ;j <= totalLoop; j++) {
if(j<32){
output += j + "\t";
}else{
output += 0 + "\t";
}
}
console.log(output);
lastJ = j;
}
output is like this
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 0 0 0 0
First of all, Welcome to SO!
A newline element after every outer loop should do the trick. Something like this.
for (var i = 1; i <= 5; i++)
{
var output = "";
for (var j = 1; j <= 7; j += 1)
{
output += "*" + "\t";
}
output += "\n";
console.log(output);
}
Edit: Realised OP wanted numbers and not *s. A simple modification to the code makes this unbelievably easy.
var output = "";
for (var i = 1; i <= 5; i++)
{
for (var j = 1; j <= 7; j += 1)
{
output += i*j + "\t";
}
output += "\n";
}
console.log(output);
}
Output - Chrome Developer Tools Screenshot

Categories

Resources