I am completely new to Javascript and trying to solve a simple problem now for more than two weeks and still not getting it(please help).
TASK ::::
Read a 4 digit Number e.g. 5678
Write a function
Split/separate the numbers and than build (5678, 567, 56, 5), than check if the numbers(5678, 567, 56, 5) are Prime numbers.
Give in Console/Result if 5678 a prime number or not, 567 a prime number or not and so on.
Check "if all numbers are Prime" than show result "All prime" if not show result "Not all prime".
Trying to solve the problem with (if else) but not really getting it, because i know very less about Javascript (arrays, string, split, slice) yet.
please help me understand. Thanks.
var a = 123456789;
var b = a.toString().length; //<<--->> ANTWORT: 9
document.write('ANTWORT: ',a );
for (i=0; i<b; i++) {
var x = a.toString().slice(0, -i);
document.write(x, ",");
}
function isPrime{
for(var i = 2; i < a; i++);
if(num % i === 0) return false;
return num > 1;
}
//integer is a string at the moment
integer = prompt("Enter a integer: ");
//initialize array for dictionary
dictArray = [];
stuff = document.getElementById("stuff");
//loop through all values of the string
for (var i = integer.length; i > 0; i--)
{
//take a substring from 0 to the ith char and turn it into an int
num = parseInt(integer.substring(0, i));
//add a dictionary to the array the tells what the number is
//and if it was prime or not as a bool
dictArray.push({"num": num, "prime": isprime(num)});
(dictArray[integer.length - i]["prime"]) ? stuff.innerHTML += "<br>" + num + " is prime." : stuff.innerHTML += "<br>" + num + " is not prime.";
}
function isprime(num)
{
if (num <= 3) return num >= 1;
if ((num % 2 === 0) || (num % 3 === 0)) return false;
let count = 5;
while (Math.pow(count, 2) <= num) {
if (num % count === 0 || num % (count + 2) === 0) return false;
count += 6;
}
return true;
}
//print the array
(dictArray.find(x => !x.prime) == undefined) ? stuff.innerHTML += "<br>All prime!" : stuff.innerHTML += "<br>Not all prime!";
//console.log(dictArray);
<div id="stuff">
</div>
Related
I want to have a logic where if I enter an even number I want next 10 even numbers to be printed and If I enter an odd number, I want next 10 odd numbers to be printed. How should I rectify this logic inside a function. If someone can please help me rectifying the logic which was answered.
JS
function oddEven() {
var input = prompt("");
for (let x = 1; x <= 10; x++) {
console.log(input + x * 2);
}
}
oddEven()
This should work for any number
const input = 2
for (let x = 1; x <= 10; x += 1) {
console.log(input + x * 2)
}
i hope this help
function printTen(input){
let list = []
let number = input
while(list.length <= 10){
number++
if(input % 2 === 0 && number % 2 === 0){
console.log(number + " is even");
list.push(number)
}else if(input % 2 !== 0 && number % 2 !== 0) {
console.log(number + " is odd");
list.push(number)
}
}
}
printTen(9)
let inputval = 2;
for (let x = 1; x <= 10; x++) {
console.log(inputval + x * 2)
}
while (a) {
b.push(a % 10);
a = Math.floor(a / 10);
if (b == 7) {
n = n + 1;
}
console.log("<br><br>number of 7's:" + n);
}
This is what I have come up with. The output is one of the numbers has seven; if not, then zero. I want the program to count the number of times seven appears in a number.
You can convert the number to a string, and then count how many times a character = 7:
let n = 7326577
let cnt = 0;
let strN = '' + n;
for(let c of strN)
if(c == '7')
cnt ++
console.log('Number of 7\'s in number: ' + cnt)
Following you approach you need to store the last digit to a different variable and use that for checking if it is a 7
var a = 709728457;
var b = [];
var n = 0;
while (a) {
const lastDigit = a % 10;
b.push(lastDigit); // if you still need to store all digits
a = Math.floor(a / 10);
if (lastDigit == 7) {
n = n + 1;
}
}
console.log("number of 7's:" + n);
var a = 7686774737
var no = String(a).split('').filter(e=>e==7).length;
console.log(no)
I want to write a function that inserts dashes (' - ') between each two odd numbers and inserts asterisks (' * ') between each two even numbers. For instance:
Input: 99946
Output: 9-9-94*6
Input: 24877
Output: 2*4*87-7
My try
function dashAst (para) {
let stringArray = para.toString().split('');
let numbArray = stringArray.map(Number);
for (let i = 0; i<numbArray.length; i++) {
if (numbArray[i] %2 === 0 && numbArray[i+1] % 2 === 0) {
numbArray.splice(numbArray.indexOf(numbArray[i]), 0, '*')
}
else if (numbArray[i] %2 !== 0 && numbArray[i+1] %2 !== 0) {
numbArray.splice(numbArray.indexOf(numbArray[i]), 0, '-')
}
}
return numbArray
}
When I try to invoke the function it returns nothing. For instance, I tested the splice-command separately and it seems to be correct which makes it even more confusing to me. Thanks to everyone reading, or even helping a beginner out.
Looping through an Array that changes its length during the loop can be very messy (i needs to be adjusted every time you splice). It's easier to create a new result variable:
function dashAst(para) {
const stringArray = para.toString().split('');
const numbArray = stringArray.map(Number);
let result = "";
for (let i = 0; i < numbArray.length; i++) {
const n = numbArray[i], next = numbArray[i + 1];
result += n;
if (n % 2 == next % 2) {
result += n % 2 ? '-' : '*';
}
}
return result;
}
console.log(dashAst(99946)); // "9-9-94*6"
console.log(dashAst(24877)); // "2*4*87-7"
You could map the values by checking if the item and next item have the same modulo and take a separator which is defined by the modulo.
function dashAst(value) {
return [...value.toString()]
.map((v, i, a) => v % 2 === a[i + 1] % 2 ? v + '*-'[v % 2] : v)
.join('');
}
console.log(dashAst(99946)); // 9-9-94*6
console.log(dashAst(24877)); // 2*4*87-7
I hope this helps
var str = '24877';
function dashAst (para) {
let stringArray = para.toString().split('');
let numbArray = stringArray.map(x => parseInt(x));
console.log(numbArray);
var out=[];
for(let i = 0; i < numbArray.length; i++) {
if(numbArray[i] % 2 == 0){
out.push(numbArray[i]);
numbArray[i + 1] % 2 == 0 ? out.push('*') : 0;
}else if(numbArray[i] % 2 != 0) {
out.push(numbArray[i]);
numbArray[i + 1] != undefined ? out.push('-') : 0;
}
}
console.log(out.join(''));
return out;
}
dashAst(str);
I'm programming a method in JavaScript/JQuery which converts the value an user enters in an inputbox. The meaning is to make this input regional aware.
The functionality contains removing zeros at the beginning, placing thousand seperators and a decimal separator.
In this use case is the , symbol a thousand separator and the . dot the decimal separator
For example following input gets converted in following output.
12300 => 12,300.00
100 => 100.00
1023.456 => 1,023.456
Now There is still a problem with numbers, less than 100.
For example following input is malformed:
1 => 1,.00
2.05 => .05
20 => 20,.00
25.65 => .65
When I don't enter a decimal value in the input box, I get an unneeded thousand separator. When I enter a decimal value, I lose my content before the decimal separator.
The code:
$("#queryInstructedAmountFrom").change(function(){
var amount = $("#queryInstructedAmountFrom").val();
amount = removeZeros(amount);
var nonFractions = amount.match(/.{1,3}/g);
if(nonFractions == null) {
nonFractions = [];
nonFractions.push(amount);
}
var splittedValues = amount.split(/[,.]/);
amount = "";
if(splittedValues.length == 1) {
amount += splittedValues[0];
nonFractions = amount.match(/.{1,3}/g);
var firstIndex = amount.length % 3;
if(firstIndex != 0) {
var firstNumbers = amount.substr(0, firstIndex);
amount = amount.substr(firstIndex);
nonFractions = amount.match(/.{1,3}/g);
if(nonFractions == null) {
nonFractions = [];
nonFractions.push(amount);
}
amount = "";
amount += firstNumbers;
amount += thousandSeparator;
} else {
amount = "";
}
for(var i=0 ; i < nonFractions.length ; i++) {
amount += nonFractions[i];
if(i < (nonFractions.length - 1) && nonFractions.length != 1){
amount += thousandSeparator;
}
}
amount += decimalSeparator;
amount += "00";
} else {
for(var i=0 ; i < splittedValues.length - 1 ; i++) {
amount += splittedValues[i];
}
nonFractions = amount.match(/.{1,3}/g);
var firstIndex = amount.length % 3;
if(firstIndex == 0) {
nonFractions = amount.match(/.{1,3}/g);
}
if(firstIndex >= 1 && nonFractions != null) {
var firstNumbers = amount.substr(0, firstIndex);
amount = amount.substr(firstIndex);
nonFractions = amount.match(/.{1,3}/g);
if(nonFractions != null) {
amount = "";
amount += firstNumbers;
amount += thousandSeparator;
} else {
nonFractions = [];
nonFractions.push(amount);
}
} else {
amount = "";
}
for(var i=0 ; i < nonFractions.length ; i++) {
amount += nonFractions[i];
if(i < (nonFractions.length - 1) && nonFractions.length != 1){
amount += thousandSeparator;
}
}
amount += decimalSeparator;
amount += splittedValues[splittedValues.length -1];
}
$("#queryInstructedAmountFrom").val(amount);
});
});
function removeZeros(amount) {
while (amount.charAt(0) === '0') {
amount = amount.substr(1);
}
if(amount.length == 0){
amount = "0";
}
return amount;
}
What is going wrong?
What is going wrong?
I'd say almost everything. You have very unclear, messy code, I hardly following your logic, but you have several critical logic mistakes in code, for example:
1
1 is converted to 1,.00 because:
var splittedValues = amount.split(/[,.]/);
creates array with single element ['1']
var firstIndex = amount.length % 3;
1%3 == 1, so you're going into if condition, where amount += thousandSeparator; appends thousand separator, but you should add separator only if you have something after that
2
2.05 is wrong, because it goes into this branch:
var firstNumbers = amount.substr(0, firstIndex); // stores '2' into firstNumbers
amount = amount.substr(firstIndex); // sets amount to empty string
later, nonFractions is null:
nonFractions = [];
nonFractions.push(amount);
but firstNumbers is not used at all, ie its value is lost
3
also, you have:
nonFractions = amount.match(/.{1,3}/g);
var firstIndex = amount.length % 3;
if (firstIndex == 0) {
nonFractions = amount.match(/.{1,3}/g);
}
what is the sense of nonFractions re-init?
probably there are more errors and edge cases where this code fails, I suggest you to use library (like in other answers) or if you want to have your own code, here is simple version you can use:
$(document).ready(function() {
$("#queryInstructedAmountFrom").change(function() {
var val = parseFloat(('0' + $("#queryInstructedAmountFrom").val()).replace(/,/g, '')); // convert original text value into float
val = ('' + (Math.round(val * 100.0) / 100.0)).split('.', 2);
if (val.length < 2) val[1] = '00'; // handle fractional part
else while (val[1].length < 2) val[1] += '0';
var t = 0;
while ((val[0].length - t) > 3) { // append thousand separators
val[0] = val[0].substr(0, val[0].length - t - 3) + ',' + val[0].substr(val[0].length - t - 3);
t += 4;
}
$("#queryInstructedAmountFrom").val(val[0] + '.' + val[1]);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="queryInstructedAmountFrom">
Why don't you use jQuery-Mask-Plugin?
<input type="text" id="money" />
and just invoke the plugin:
$('#money').mask('000.000.000.000.000,00', {reverse: true});
Plunker: https://plnkr.co/edit/PY7ihpS3Amtzeya9c6KN?p=preview
Refer to the below code updated.
$(document).ready(function() {
$("#queryInstructedAmountFrom").change(function() {
var amount = $("#queryInstructedAmountFrom").val();
amount = removeZeros(amount);
// format amount using 'ThousandFormattedValue' function
amount = ThousandFormattedValue(amount);
$("#queryInstructedAmountFrom").val(amount);
});
});
function removeZeros(amount) {
while (amount.charAt(0) === '0') {
amount = amount.substr(1);
}
if (amount.length == 0) {
amount = "0";
}
return amount;
}
function ThousandFormattedValue(iValue) {
// declaring variables and initializing the values
var numberArray, integerPart, reversedInteger, IntegerConstruction = "",
lengthOfInteger, iStart = 0;
// splitting number at decimal point by converting the number to string
numberArray = iValue.toString().split(".");
// get the integer part
integerPart = numberArray[0];
// get the length of the number
lengthOfInteger = integerPart.length;
// if no decimal part is present then add 00 after decimal point
if (numberArray[1] === undefined) {
numberArray.push("00");
}
/* split the integer part of number to individual digits and reverse the number
["4" , "3" , "2" , "1"] - after split
["1" , "2" , "3" , "4"] - after reverse
"1234" - after join
*/
reversedInteger = integerPart.split("").reverse().join("");
// loop through the string to add commas in between
while (iStart + 3 < lengthOfInteger) {
// get substring of very 3 digits and add "," at the end
IntegerConstruction += (reversedInteger.substr(iStart, 3) + ",");
// increase counter for next 3 digits
iStart += 3;
}
// after adding the commas add the remaining digits
IntegerConstruction += reversedInteger.substr(iStart, 3);
/* now split the constructed string and reverse the array followed by joining to get the formatted number
["1" , "2" , "3" , "," ,"4"] - after split
["4" , "," , "3" , "2" , "1"] - after reverse
"4,321" - after join
*/
numberArray[0] = IntegerConstruction.split("").reverse().join("");
// return the string as Integer part concatinated with decimal part
return numberArray.join(".");
}
var sum = 0
for (i = 0; i < 250; i++) {
function checkIfPrime() {
for (factor = 2; factor < i; factor++) {
if (i % factor = 0) {
sum = sum;
}
else {
sum += factor;
}
}
}
}
document.write(sum);
I am trying to check for the sum of all the prime numbers under 250. I am getting an error saying that i is invalid in the statement if (i % factor = 0) I know was creating in the original for statement, but is there any way to reference it in the if statement?
With the prime computation, have you considered using Sieve of Eratosthenes? This is a much more elegant way of determining primes, and, summing the result is simple.
var sieve = new Array();
var maxcount = 250;
var maxsieve = 10000;
// Build the Sieve, marking all numbers as possible prime.
for (var i = 2; i < maxsieve; i++)
sieve[i] = 1;
// Use the Sieve to find primes and count them as they are found.
var primes = [ ];
var sum = 0;
for (var prime = 2; prime < maxsieve && primes.length < maxcount; prime++)
{
if (!sieve[prime]) continue;
primes.push(prime); // found a prime, save it
sum += prime;
for (var i = prime * 2; i < maxsieve; i += prime)
sieve[i] = 0; // mark all multiples as non prime
}
document.getElementById("result").value =
"primes: " + primes.join(" ") + "\n"
+ "count: " + primes.length + "\n"
+ "sum: " + sum + "\n";
#result {
width:100%;
height:180px
}
<textarea id="result">
</textarea>
(EDIT) With the updated algorithm, there are now two max involved:
maxcount is the maximum number of prime numbers you wish to find
maxsieve is a guess of sieve large enough to contain maxcount primes
You will have to validate this by actually checking the real count since there are two terminating conditions (1) we hit the limit of our sieve and cannot find any more primes, or (2) we actually found what we're looking for.
If you were to increase the number to numbers much greater than 250, than the Sieve no longer becomes viable as it would be consume great deals of memory. Anyhow, I think this all makes sense right? You really need to play with the Sieve yourself at this point than rely on my interpretation of it.
You can equally use this
let sum = 0;
let num = 250;
for (let i = 2; i < num; i++) {
let isPrime = true;
for (let j = 2; j < i; j++) {
if (i % j === 0) {
isPrime = false;
}
}
if (isPrime) {
sum += i;
}
}
console.log(sum);
i % factor === 0
Use === for comparison. = is for assignment. Yeah I said triple equals. Type coercion is annoying.
You need a == or ===: if (i % factor == 0)
Here's a pretty decent way to do it. It's not as advanced as the sieve but it's a decent starting point. NOTE: I'm using ES6 syntax.
/*
* Sum the first n prime numbers
*
* #param n (integer)
* #return integer
*
*/
function sumNprimes(n){
const arr = [];
let i = 2
while (arr.length < n) {
if (isPrime(i)) {
arr.push(i)
}
i++
}
return arr.reduce( (x,y) => x+y );
/*
* #param n (integer)
* #return Boolean
*
*/
function isPrime(n) {
if ( n < 2 ) {
return false
}
for ( let i = 2; i <= Math.sqrt(n); i++ ) {
if ( n % i === 0 ) {
return false;
}
}
return true
}
}
So i had to face a similar challenge and here is my solution, i hope you find it helpful:
function sumPrimes(num) {
// determine if a number is prime
function isPrime(n) {
if (n === 2) return true;
if (n === 3) return true;
if (n % 2 === 0) return false;
if (n % 3 === 0) return false;
var i = 5;
var w = 2;
while (i * i <= n) {
if (n % i === 0) {
return false;
}
i += w;
w = 6 - w;
}
return true;
}
// subtract 1 for 'not being prime' in my context
var sum = isPrime(num) ? num - 1 : -1;
for (var x = 0; x < num; x++) {
if (isPrime(x) === true) {
sum += x;
}
}
return sum;
}
As per the "Sieve of Eratosthenes", I have implemented the code using JS:
function isPrime(n){
return ((n/2 === 1 || n/3 === 1 || n/5 === 1 || n/7 === 1)?true:(n%2===0 || n%3 === 0 || n%5 ===0 || n%7 === 0)?false:true);
};
var val = 250;
let outArr = [];
for(let i=2;i<val;i++){
if(isPrime(i)){
outArr.push(i);
}
}
console.log("Prime number between 0 - "+val+" : "+outArr.join(","));
Here is a simple way of looping through array and implementing the sieve of Eratosthenes...
function sumPrimes(num) {
var t, v = [],
w = [],
x = [],
y = [],
z = 0;
//enumerating Vee array starts at 2 as first prime number
for (let a = 2; a <= num; a++) {
v.push(a)
}
//creating a moving loop by splicing its first index
for (let i = 0; i < v.length; i) { //ensure all items spliced
t = v[i]; // t as prime to be removed from Vee array
x.push(t); // x storage of primes
z += t // total of peculiar primes
w.push(v.splice(i, 1)) //tested to move all one by one
// prompt(v) //tested that v loses its v[i] every iteration
//= now trying to remove others using remainder (%) vs prime t
for (let vi in v) {
v[vi] % t === 0 ? y.push(v.splice(vi, 1)) : ""; //recursive removal of composite items by prime t
}
}
return z // returns sum of primes
}
sumPrimes(250);
You generate the array beginning with 2 as first prime,
You sieve the array removing items by the remainder of prime using % === 0.
The you loop through the remaining array by using the next prime until the last remaining prime is pushed to the prime arrays. Add all primes to get the Sum.
If the question is purely academical, earlier answers are better suited.
The example below uses modern libraries, in case you need an efficient and elegant solution.
import {generatePrimes} from 'prime-lib';
import {from, reduce, takeWhile} from 'rxjs';
from(generatePrimes())
.pipe(takeWhile(p => p < 250), reduce((a, c) => a + c))
.subscribe(sum => {
// sum = 5830
});
Performance-wise, it will take significantly less than 1ms.
How would it affect the code if I wanted say the sum of the first 250 prime numbers instead of the prime numbers under 250?
You would just replace takeWhile(p => p < 250) with take(250):
import {generatePrimes} from 'prime-lib';
import {from, reduce, take} from 'rxjs';
from(generatePrimes())
.pipe(take(250), reduce((a, c) => a + c))
.subscribe(sum => {
// sum = 182109
});
P.S. I am the author of prime-lib.