Pascal’s triangle is in infinity

Asked

Viewed 82 times

1

I’m making a code that generates a Pascal triangle for a project of mine, but when I spin it gets stuck, as if the is infinite.

function pascal(n) {
	var d;
	var uau = "";
	var line;
	var i;
	for(line = 1; line += 1; line <= n){
		d = 1;
		for(i = 1; i += 1; i <= line){
			uau += d.toString();
			d *= (line - i) / i;
		}
		uau += "<br>";
	};
	return uau;
}

$("#uau").click(function(){
	var n = $("#inp").val();
	document.write(pascal(n));
});
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>teste</title>
	<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
</head>
<body>
	<form>
		<input type="number" id="inp">
		<button type="button" id="uau">UAU</button>
	</form>
</body>
</html>

1 answer

3


The main problem is that it is incrementing where it should place the end condition of the loop and is placing the condition where action should be executed at each step of the loop. Reversing this solves the problem. I took advantage and simplified a little, but could give better names for variables as well. I took the part that was not related to the problem to demonstrate working more easily.

I think there are other problems even logic of what you are doing, the formula is probably not this, but I answered what was asked, even because the other errors are not programming.

function pascal(n) {
    var uau = "";
    for (var line = 1, d = 1; line <= n; line++) {
        for (var i = 1; i <= line; i++) {
            uau += d.toString();
            d *= (line - i) / i;
        }
        uau += "<br>";
    };
    return uau;
}
console.log(pascal(10));

I put in the Github for future reference.

  • Thank you, you saved me

Browser other questions tagged

You are not signed in. Login or sign up in order to post.