I can't figure this problem out, I already checked my code but I don't know what the problem is.
This is the question: A mathematician Ulam proposed generating a sequence of numbers from any positive integer n (n>0) as follows.
if n is 1, it will stop.
if n is even, the next number is n/2.
if n is odd, the next number is 3 * n + 1.
continue with the process until reaching 1.
here some examples for the first few integers.
2->1
3->10->5->16->8->4->2->1
4->2->1
6->3->10->5->16->8->4->2->1
7->22->11->34->17->52->26->13->40->20->10->5->16->8->4->2->1
Sample Run:
Enter Positive Integer: 5
The ulam Number Sequence is : 5->16->8->4->2->1
this is my code...
<!DOCTYPE html>
<html>
<head>
<title>Ulam Number Sequence</title>
</head>
<body>
<form name="myform" onsubmit=" return false">
Enter positive integer: <input type="number" id="num" required>
<button onclick="process()">Process</button>
<button onclick="Reset()">Reset</button>
</form>
<p id = "info"> </p>
<script>
function isOdd(num) {
var odd = true;
for (var i = 0; i <= num; i++) {
if (num % i == 0) {
odd = false;
break;
}
}
return odd;
}
function isEven(num) {
var even = true;
for (var i = 0; i <= num; i++) {
if (num % i == 1) {
even = false;
break;
}
}
return even;
}
function process(){
var n = parseInt(document.getElementById("num").value);
var result1 = [];
for(var i = 0; i <= n; i++){
if(isOdd(i)){
result1[result1.length] = i /2;
}
if(isEven(i)){
result1[result1.length] = 3 * i + 1;
}
if(isOdd(result1)){
result1[result1.length] = result1 / 2;
}
if(isEven(result1)){
result1[result1.length] = 3 * result1 +1;
}
//result1[result1.length] = i * 3 + 1;
document.getElementById("info").innerHTML = result1.join("->");
}
}
function Reset(){
document.getElementById("info").innerHTML = "";
document.getElementById("num").value = "" ;
}
</script>
</body>
</html>
Maybe this is a solution for you (and a little hint):
function process() {
var n = parseInt(document.getElementById('num').value),
result = [n];
if (isFinite(n) && n && n === Math.abs(n)) {
while (n !== 1) {
// basically this is all to do.
n = n % 2 ? 3 * n + 1 : n / 2;
result.push(n);
}
document.getElementById("info").innerHTML = result.join(' > ');
} else {
document.getElementById("info").innerHTML = 'Does not compute!';
}
}
function reset() {
document.getElementById('info').innerHTML = '';
document.getElementById('num').value = ''
}
<form name="myform" onsubmit=" return false">
Enter positive integer: <input type="number" id="num" required>
<button onclick="process()">Process</button>
<button onclick="reset()">Reset</button>
</form>
<p id="info"></p>
Related
I am stuck here with duch issue. There are 2 two entry boxes are for an amount and an interest rate (%).
If you click on the button, the page will show an overview of the balance until the amount have to be doubled.
Taking a simple numbers forexample 10 - is amount and 4 - is 4% intereste rate. So the result have to stop on amount of 20.
document.getElementById("button").onclick = loop;
var inputB = document.getElementById("inputB");
var inputC = document.getElementById("inputC");
var result = document.getElementById("result")
function loop() {
var s = inputB.value;
var r = inputC.value;
var doubleS = s * 2;
for (var i = 1; i <= doubleS; i++) {
s = ((r / 100 + 1) * s);
result.innerHTML += s + "<br>";
}
}
<! DOCTYPE html>
<html>
<body>
<br>
<input type="text" id="inputB" value="10"><br>
<input type="text" id="inputC" value="4"><br><br>
<button id="button">Klik</button>
<p> De ingevoerde resultaten: </p>
<p id="result"></p>
<script async src="oefin1.js"></script>
</body>
</html>
The issue is with your for loop bounds.
This will loop doubleX number of times: for (var i = 0; i < doubleX; i++)
This will loop until x surpasses doubleX: for (;x < doubleX;), which btw is better written with a while loop: while (x < doubleX)
document.getElementById("button").onclick = loop;
var inputB = document.getElementById("inputB");
var inputC = document.getElementById("inputC");
var result = document.getElementById("result")
function loop() {
var s = inputB.value;
var r = inputC.value;
var doubleS = s * 2;
result.innerHTML = '';
while (s < doubleS) {
s = ((r / 100 + 1) * s);
result.innerHTML += s + "<br>";
}
}
<input type="text" id="inputB" value="10"><br>
<input type="text" id="inputC" value="4"><br><br>
<button id="button">Klik</button>
<p> De ingevoerde resultaten: </p>
<p id="result"></p>
Easiest way is to just use a for loop without the convoluted math with s in the middle:
function loop() {
var s = inputB.value;
var r = inputC.value;
var doubleS = s * 2;
for (var i = s; i <= doubleS; i *= ((r / 100) + 1)) {
result.innerHTML += i + "<br>";
}
}
use a while loop and check is the value of s is bigger than or equal to doubleS
document.getElementById("button").onclick = loop;
var inputB = document.getElementById("inputB");
var inputC = document.getElementById("inputC");
var result = document.getElementById("result")
function loop() {
var s = inputB.value;
var r = inputC.value;
var doubleS = s * 2;
while(true) {
s = ((r / 100 + 1) * s);
result.innerHTML += s + "<br>";
if(s >= doubleS){
break
}
}
}
<! DOCTYPE html>
<html>
<body>
<br>
<input type="text" id="inputB" value="10"><br>
<input type="text" id="inputC" value="4"><br><br>
<button id="button">Klik</button>
<p> De ingevoerde resultaten: </p>
<p id="result"></p>
<script async src="oefin1.js"></script>
</body>
</html>
The code below returns me 'even' or 'odd', but I have to always change, what to do for him to check 25 to 115 and show result in the body of the page?
<html>
<title>FrontPage</title>
</head>
<body>
<form method="post" name="Form1" onsubmit="Check();">
<input type="submit" value="Submit" name="bSubmit"></p>
</form>
<script type="text/javascript">
function Check() {
var n = "26";
var finish = n/2;
if(n & 1){
alert("Impar");
} else {
alert("Par");
}
alert(finish);
}
</script>
</body>
</html>
var btn = document.querySelector('#btn');
var result = document.querySelector('#result');
btn.addEventListener('click', function() {
for (var i = 25; i <= 115; i++) {
var li = document.createElement('li');
li.innerText = i.toString() + ' - ' + ((i & 1) ? 'Impar' : 'Par');
result.append(li);
}
});
<input id="btn" type="submit" value="Submit" name="bSubmit">
<ul id="result"></ul>
Just implement your code within a for-loop (since you know exactly how many iterations you need):
document.querySelector('#btnSubmit').addEventListener('click', function(e) {
var min = 25;
var max = 115;
var i;
for (i = min; i <= max; i += 1) {
console.log(check(i));
}
});
function check(n) {
var s = `${n} is `;
s += n % 2 === 0 ? "even" : "odd";
return s;
}
check();
<input id="btnSubmit" type="button" value="Check" />
You need to use the foor loop like so:
const append = str => document.getElementById('print').innerHTML += str;
document.getElementById('btn').addEventListener('click', function () {
for (let i = 25; i <= 115; i++) {
const result = i % 2 === 0 ? 'even' : 'odd';
append(`<p>Number ${i} is ${result}</p>`);
}
});
<button id="btn">Result</button>
<div id="print"></div>
I was excited because my prime number program was working, but when I tried certain numbers like 5 and 10, 2 and 11, it wasn't working. I have tried to figure it out myself, and by looking at other things related to what I was doing, but I couldn't figure it out. I would appreciate an answer and thank everyone who helps, because I am just a beginner at coding and want to learn more.
var minimum;
var maximum;
var primes;
function myFunction(e) {
e.preventDefault();
minimum = document.getElementById('Minimum').value;
maximum = document.getElementById('Maximum').value;
primes = [];
listOfPrimes(minimum, maximum);
primes = primes.filter(function(x) {
return x > 1;
});
primes = primes.toString();
primes = primes.replace(/,(?=[^\s])/g, ", ");
document.getElementById("Your_Primes").innerHTML = primes;
}
function isPrime(num) {
for (var i = 2; i <= num / 2; i++)
if (num % i === 0) {
return false;
}
primes.push(num);
}
function listOfPrimes(min, max) {
for (var j = min; j <= max; j++) {
isPrime(j);
}
}
body {
background-color: #dbdbdb;
}
#prime-checker {
background-color: #89a9dd;
margin: 5px;
padding: 5px;
text-align: center;
}
.the-primes {
background-color: #587cb7;
padding: 15px;
margin: 10px;
}
<!doctype html>
<html>
<head>
<title>Prime Lister</title>
<link href="main.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="prime-checker">
<form>
<h2>Minimum Number:</h2><br>
<input type="number" placeholder="MinimumWholeNumber" id="Minimum" multiple="1" min="0" required><br><br>
<h2>Maximum Number:</h2><br>
<input type="number" placeholder="MaximumWholeNumber" id="Maximum" multiple="1" min="0" required><br><br><br>
<button id="button" onclick="myFunction(event)">Enter</button>
</form>
<div class="the-primes"><h2>Your Primes:</h2>
<p id="Your_Primes"></p>
</div>
</div>
<script type="text/javascript" src="Web_Prime_Lister.js"></script>
</body>
</html>
Your code for calculating a prime looks fine. The problem is that you are using the raw strings from the minimum and maximum to create your range. The problem is that strings are compared lexigraphically, so:
"2" < "100" // false
So when you pass those values into your function listOfPrimes, that loop will terminate early due to the string comparison.
To fix it, just convert your input values to numbers before you use them:
minimum = Number(document.getElementById('Minimum').value);
maximum = Number(document.getElementById('Maximum').value);
Here's your snippet with that fix, everything looks like it's working well:
var minimum;
var maximum;
var primes;
function myFunction(e) {
e.preventDefault();
minimum = Number(document.getElementById('Minimum').value);
maximum = Number(document.getElementById('Maximum').value);
primes = [];
listOfPrimes(minimum, maximum);
primes = primes.filter(function(x) {
return x > 1;
});
primes = primes.toString();
primes = primes.replace(/,(?=[^\s])/g, ", ");
document.getElementById("Your_Primes").innerHTML = primes;
}
function isPrime(num) {
for (var i = 2; i <= num / 2; i++)
if (num % i === 0) {
return false;
}
primes.push(num);
}
function listOfPrimes(min, max) {
for (var j = min; j <= max; j++) {
isPrime(j);
}
}
body {
background-color: #dbdbdb;
}
#prime-checker {
background-color: #89a9dd;
margin: 5px;
padding: 5px;
text-align: center;
}
.the-primes {
background-color: #587cb7;
padding: 15px;
margin: 10px;
}
<!doctype html>
<html>
<head>
<title>Prime Lister</title>
<link href="main.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="prime-checker">
<form>
<h2>Minimum Number:</h2><br>
<input type="number" placeholder="MinimumWholeNumber" id="Minimum" multiple="1" min="0" required><br><br>
<h2>Maximum Number:</h2><br>
<input type="number" placeholder="MaximumWholeNumber" id="Maximum" multiple="1" min="0" required><br><br><br>
<button id="button" onclick="myFunction(event)">Enter</button>
</form>
<div class="the-primes"><h2>Your Primes:</h2>
<p id="Your_Primes"></p>
</div>
</div>
<script type="text/javascript" src="Web_Prime_Lister.js"></script>
</body>
</html>
PS: You can further optimize your isPrime function by only checking divisors up to Math.floor(Math.sqrt(num)). That will save you many many iterations, especially for a large number. So:
function isPrime(num) {
var max = Math.floor(Math.sqrt(num));
for (var i = 2; i <= max; i++)
if (num % i === 0) {
return false;
}
primes.push(num);
}
As you can see, for a 10-digit prime, the running time is very much reduced:
function isPrimeSqrt(num) {
var max = Math.floor(Math.sqrt(num));
for (var i = 2; i <= max; i++)
if (num % i === 0) {
return false;
}
return true;
}
function isPrimeHalf(num) {
var max = Math.floor(num / 2);
for (var i = 2; i <= max; i++)
if (num % i === 0) {
return false;
}
return true;
}
let now = Date.now();
const pHalf = isPrimeHalf(1010189899);
console.log("Using 'Half' took:", Date.now() - now, "ms. Is prime:", pHalf);
now = Date.now()
const pSqrt = isPrimeSqrt(1010189899);
console.log("Using 'Sqrt' took:", Date.now() - now, "ms. Is prime:", pSqrt);
Got it!
Simply change this line:
for (var j = min; j <= max; j++) {
to this:
for (var j = parseInt(min); j <= parseInt(max); j++) {
Get familiar with Debugger Tools (F12 in most browsers). There you can pause execution in certain lines and check value and type of variables. If you do it, there you'll see than min = "5", insted of min = 5. That's why 5-49 doesn't work, beacuse "5" is smaller than "49" (beacuse it's first digit is lower), so it doesn't loop at all.
I have created a conversion table which converts miles to kilometres and kilometres to miles depending on whichever one the user chooses. They input two numbers which indicates the two ranges so if they input 2 and 5 and choose km to m it will then show 2km to 5km converted to miles. However, what I am trying to do is if the user inputs a greater number to start with for instance if you enter 10 and 2 it should still do the same but rather it should go from 10km down to 2km so in descending order, so I know it will be something along the lines of if(rangeStart>rangeEnd){i--;}
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
function conversion(n) {
if (document.getElementById('mtokm').checked) {
return (n/0.62137).toFixed(2);
}
else {
return (n*0.62137).toFixed(2);
}
}
function conversionTable(rangeStart, rangeEnd) {
if(atLeastOneRadio() && rangeStart != false && rangeEnd != false) {
divStr="<table border=1><tr><td>Miles</td><td>Kilometres</td></tr>";}
for(i=rangeStart;i<=rangeEnd;i++) {
if(i%2==0)
{
divStr+= "<tr bgcolor=\"yellow\"><td>" + i + "</td><td>" + conversion(i) + "</td></tr>";
}
else
{
divStr+= "<tr bgcolor=\"green\"><td>" + i + "</td><td>" + conversion(i) + "</td></tr>";
}
}
document.getElementById("divResult").innerHTML=divStr;
}
else
{
alert("Please make sure you have entered an integer in both text boxes");
}
}
function getnputValue(input) {
var nn = $("input[name=convert]:checked").val()
var myInt = document.getElementById(input).value;
if(myInt == parseInt(myInt))
return parseInt(myInt);
else
return false;
}
function check() {
var radios = document.getElementsByName("choice");
$("input[name=convert]:checked").val()
for (var i = 0, len = radios.length; i < len; i++) {
if (radios[i].checked) {
return true;
}
}
return false;
}
function atLeastOneRadio() {
return ($('input[type=radio]:checked').length > 0);
}
</script>
</head>
<body>
<p>
Start : <input type=textbox id=rangeTxt value=""/>
End : <input type=textbox id=rangeTxt2 value=""/>
<input type=radio name="convert" id="mtokm" value ="Miles to Kilometre"/> Miles to Kilometre
<input type=radio name="convert" id="kmtom" value ="Kilometre to Miles"/> Kilometre to Miles
<br>
<br>
<button onClick="conversionTable(getnputValue('rangeTxt'), getnputValue('rangeTxt2'))">Convert</button>
</p>
<div id="divResult">
</div>
</body>
</html>
Check whether the end is higher or lower than the start. Then set variables that are used to control the for loop.
var increment, compare;
if (rangeStart <= rangeEnd) {
increment = 1;
compare = function(x, y) {
return x <= y;
};
} else {
increment = -1;
compare = function(x, y) {
return x >= y;
};
}
for (i = rangeStart; compare(i, rangeEnd); i += increment) {
// display code
}
I have worked for a while on this code for learning purposes. I finally got the program to work, however when you "roll the dice", it only allows the dice to be rolled 1 time; If you wish to roll the dice a second time you must refresh the screen.
I am trying to build a reset function for this program so that I can roll the dice as many times as I wish without a screen-refresh.
I have built the reset function, but It is not working... It clear's the DIV's, but doesn't allow the program to be executed again.
Can someone please help me out?
*I am a semi-noobie at Javascript, I am making programs like this to practice my skills.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dice Rolling</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<header>
<h1>Roll the Dice!</h1>
<h2>By: Jeff Ward</h2>
</header>
<h3>Setup your Dice!</h3>
<div id="left">
<form id="numberOfDiceSelection">
Number Of Dice Used:
<br>
<input id="numberOfDice" type="text" name="numberOfDice">
</form>
</div>
<div id="right">
<form id="diceSidesSelection">
Number of sides on each dice:
<br>
<input id="diceSides" type="text" name="diceSides">
</form>
</div>
<button type="button" onclick="roll()">Roll the Dice!</button>
<button type="button" onclick="reset()">Reset Roll</button>
<div id="output">
</div>
<div id="output1">
</div>
<script src="js/script.js"></script>
</body>
</html>
JavaScript:
function roll() {
var text = "";
var sides = +document.getElementById("diceSides").value;
var dice = +document.getElementById("numberOfDice").value;
var rolls = [];
// --------Ensures both Numbers are Intergers-----------
if (isNaN(sides) || isNaN(dice)) {
alert("Both arguments must be numbers.");
}
// --------Loop to Print out Rolls-----------
var counter = 1;
do {
roll = Math.floor(Math.random() * sides) + 1;
text += "<h4>You rolled a " + roll + "! ----- with dice number " + counter + "</h4>";
counter++;
rolls.push(roll);
}
while (counter <= dice)
document.getElementById("output").innerHTML = text;
// --------Double Determination-----------
var cache = {};
var results = [];
for (var i = 0, len = rolls.length; i < len; i++) {
if (cache[rolls[i]] === true) {
results.push(rolls[i]);
} else {
cache[rolls[i]] = true;
}
// --------Print amount of Doubles to Document-----------
}
if (results.length === 0) {} else {
document.getElementById("output1").innerHTML = "<h5> You rolled " + results.length + " doubles</h5>";
}
}
// --------RESET FUNCTION-----------
function reset() {
document.getElementById("output1").innerHTML = "";
document.getElementById("output").innerHTML = "";
document.getElementById("diceSides").value = "";
document.getElementById("numberOfDice").value = "";
text = "";
rolls = [];
}
Thank you!!
JSFiddle Link = https://jsfiddle.net/kkc6tpxs/
I rewrote and did what you were trying to do:
https://jsfiddle.net/n8oesvoo/
var log = logger('output'),
rollBtn = getById('roll'),
resetBtn = getById('reset'),
nDices = getById('numofdices'),
nSides = getById('numofsides'),
dices = null,
sides = null,
rolls = [],
doubles=0;
rollBtn.addEventListener('click',rollHandler);
resetBtn.addEventListener('click', resetHandler);
function rollHandler() {
resetView();
sides = nSides.value;
dices = nDices.value;
doubles=0;
rolls=[];
if(validateInput()) {
log('invalid input');
return;
}
//rolling simulation
var rolled;
while (dices--) {
rolled = Math.ceil(Math.random()*sides);
log('For Dice #'+(dices+1)+' Your Rolled: '+ rolled +'!');
rolls.push(rolled);
}
//finding doubles
//first sort: you can use any way to sort doesnt matter
rolls.sort(function(a,b){
return (a>b?1:(a<b)?0:-1);
});
for (var i =0; i < rolls.length; i++) {
if (rolls[i] == rolls[i+1]) {
doubles++;
i++;
}
}
if (doubles>0) log("You rolled " + doubles + " doubles");
}
function resetHandler(){
resetView();
nDices.value = nSides.value = '';
}
function resetView() {
getById('output').innerText = '';
}
function validateInput(){
return (isNaN(sides) || sides == '' || isNaN(dices) || dices == '');
}
function logger(x) { var output = getById(x);
return function(text){
output.innerText += text + '\n';
};}
function getById(x){ return document.getElementById(x); }