I'm trying to display all the prime numbers up to 10 and it isn't working. Can you see what I did wrong?
function findPrimeNumbers() {
var count = 10,
primes = [];
for (var i = 0; i <= count; i++) {
if (count / i === 1 || count) primes.push(i);
else continue;
count -= 1;
}
for (var i = 0, len = primes.length; i < len; i++) return primes[i];
}
console.log(findPrimeNumbers());
It only returns 0 in the console.
Here's about the simplest way to generate primes. Note that there are more efficient methods, but they are harder to understand.
function findPrimeNumbers (count) {
var primes = [];
for (var J = 2; J <= count; J++) {
var possPrime = true;
for (var K = 2, factorLim = Math.sqrt (J); K <= factorLim; K++) {
if (J % K == 0) {
possPrime = false;
break;
}
}
if (possPrime)
primes.push (J);
}
return primes;
}
console.log (findPrimeNumbers (10) );
This yields all the primes <= 10:
[2, 3, 5, 7]
See Wikipedia for an explanation.
for (var i = 0, len = primes.length; i < len; i++) return primes[i];
Here you are return just the first element of the array. I think you meant something like this
var retstr = "";
for (var i = 0, len = primes.length; i < len; i++)
{
//To improve str format
if(i == len-1)
retstr += primes[i];
else
retstr += primes[i] + ", ";
}
return retstr;
Hope this helps.
if (count / i === 1 || count / i === count)
You don't say how it's not working, but the first thing that comes to my attention is that you're incrementing i, while at the same time decrementing count, so i will never get all the way to 10.
Also, count / i will cause a divide-by-zero error on the first iteration as it's written (unless Javascript magically handles that case in some way I'm not familiar with).
Then you "loop" through your return values--but you can only return once from a function, so of course you're only going to return the first value.
And you are returning from the function in the last for loop. Remove that for loop, just return the array.
function PrimeCheck(n){ //function to check prime number
for(i=2;i<n;i++){
if(n%i==0){
return false
}
}
return true;
}
function print(x){ //function to print prime numbers
var primeArray=[];
for(j=2;j<x;j++){
if(PrimeCheck(j)==true){
primeArray.push(j);
}
}
console.log(primeArray);
}
print(10); //[2,3,5,7]
Related
I wanted to create a function to check if the number is prime or not. I found a solution for this challenge and I passed it. But I can't quite understand why num 2 returns as true.
If anyone could share your knowledge, it would be great!
function checkNum(i) {
for(let j = 2 ; j < i; j++) {
if(i % j === 0) {
return false;
}
the below is the whole solution.
So.... When i is 2 in this code, why does it return true? Is it because i is not greater than j? so for loop doesn't evaluate it....? and returns true?
function sumPrimes(num) {
let sum = 0;
function checkNum(i) {
for (let j = 2; j < i; j++) {
if (i % j === 0) {
return false;
}
}
return true;
}
for (let i = 2; i <= num; i++) {
if (checkNum(i)) {
sum += i;
}
}
return sum;
}
console.log(sumPrimes(10));
((s, n) => {
let nStrings = ''; // stores the string we get after multiplying s to reach length n.
let aNos = 0; // stores the number of 'a's present in nStrings;
for (let i = 0; i < n; i++) {
for (let j = 0; j < s.length; j++) {
if (nStrings.length === n) {
break;
} else {
nStrings += s[j];
}
}
}
for (let k = 0; k < nStrings.length; k++) {
if (nStrings[k] === 'a') {
aNos++;
}
}
return aNos;
})('a', 1000000000000);
Above is my code written for the problem "Repeated Strings" in Hackerrank (Problem link). I wrote this in JavaScript. When I ran this code it shows that it ran out of memory. I don't understand why.
Please review my code and let me know why it failed.
Thank you.
You could get the the count of a in the given string, divide the length by the string length, get the integer part and multiply with the count of the given string.
The second part is to get the rest of the wanted length with remainder operator and iterate the given string for getting a count of a.
Return the sum of the integer and rest count.
function getCount(string, length) {
var first = 0,
count = 0,
rest = 0,
restCount = 0,
i;
for (i = 0; i < string.length; i++) if (string[i] === 'a') count++;
first = Math.floor(length / string.length) * count;
rest = length % string.length;
for (i = 0; i < rest; i++) if (string[i] === 'a') restCount++;
return first + restCount;
}
console.log(getCount('aba', 10)); // 7
My code works in console but gives the wrong result in hackerank
Problem: Print count of all substrings that are palindromes from a string
function isPalindrome(str) {
var len = str.length;
var mid = Math.floor(len / 2);
for (var i = 0; i < mid; i++) {
if (str[i] !== str[len - 1 - i]) {
return false;
}
}
//Had to use this lengthy function because in
//str == str.split('').reverse().join('');
//I was getting error that split is not a function
return true;
}
function scatterPalindrome(str) {
var result = [],
c = 0;
for (let i = 0; i < str.length; i++) {
for (let j = i + 1; j < str.length + 1; j++) {
result.push(str.slice(i, j));
}
}
for (let i = 0; i < result.length; i++) {
let k = result[i];
if (isPalindrome(k))
c++;
}
return c; // the answer was always 1
}
console.log(scatterPalindrome("abc"));
input: "abc"
expected output: 3
actual output:1
As I can't comment, so answering here, I will say you should check if they have mentioned there are many test cases, and in each test case you have to do the query then this is reasonable that your output and their output will not match
take no.of testcases input
while(testcases counter doesn't reach 0 )
take string input
call your function for answer for input and print
decrement testcases counter
function lcm(arr) {
arr = arr.sort(function(a, b) {
return a - b;
});
var j = 1;
var num = arr[0];
for (i = 1; i < arr.length; i++) {
while (num % arr[i] !== 0) {
j = j + 1;
num = j * arr[0];
}
arr[0] = num;
}
return num;
}
console.log(lcm([3, 5, 6, 10]));
I am trying to find the least common multiple for a range of numbers in an array. The code works fine for array with two items, however the output for arrays with more than two items seems to exceed the value expected.
Can anyone help me find the bug in my code ?
Thank you
Set j back to 1 each time through the loop through the array elements. Otherwise, when you process the next number, you start with a high multiplier.
// function that find the least common multiple
function lcm(arr) {
arr = arr.sort(function(a, b) {
return a - b;
});
var num = arr[0];
for (i = 1; i < arr.length; i++) {
var j = 1;
while (num % arr[i] !== 0) {
j = j + 1;
num = j * arr[0];
}
arr[0] = num;
}
return num;
}
console.log(lcm([3, 5, 6, 10]));
A math problem describes a list of numbers from 1-200, you must skip the number 1, and then for each number that follows, remove all multiples of that number from the list. Do this until you have reached the end of the list.
Here's what I have so far.
var x = []; // creating an array called x with zero numbers
for ( var i = 1; i <= 200; i++ ){
x.push(i);
};
// x now should have an array that contains the intergers from 1-200.
//looping through the array.
for ( var i = 0; i <= x.length; i++ ){ //going from 1-200
if (x[i] == 1){
continue; // skipping 1
} else {
for ( var n = i+1; n <= i; n++){ // take the number 1 index bigger than x[i]
if ( n % i == 0){ //find if the modulus of x[n] and x[i] is zeor, meaning it is divisible by x[i]
x.shift(); //remove that number
console.log(x[n]);
} else {
continue;
}
}
}
};
Instead of adding number 1 to 200 and then removing non prime numbers, try only putting prime numbers into that list. Since this is a school problem (I'm guessing) I don't want to give you the answer, but if you have more questions I can answer.
Also your nested loop will never run, go over that logic again.
Another version (a minute too late, as always ;-), one with comments
// lil' helper
function nextSet(a,n){
while(a[n] == 0) n++;
return n;
}
function setPrimes(a,n){
var k, j, r;
n = n + 1;
k = n;
while(k--)a[k] = 1;
a[0] = 0; // number 0
a[1] = 0; // number 1
// get rid of all even numbers
for(k = 4; k < n; k += 2) {
a[k] = 0;
}
// we don't need to check all of the numbers
// because sqrt(x)^2 = x
r = Math.floor(Math.sqrt(n));
k = 0;
while(k < n){
k = nextSet(a,k+1);
// a test if we had them all
if(k > r){
break;
}
// unmark all composites
for(j = k * k; j < n; j += 2*k){
a[j] = 0;
}
}
return a;
}
function getPrimes(n){
// we know the size of the input
var primearray = new Array(n);
// we don't know the size of the output
// prime-counting is still an unsolved problem
var output = [];
setPrimes(primearray, n);
for(var i = 0; i < n; i++){
if(primearray[i] == 1){
output.push(i);
}
}
return output;
}
getPrimes(200);
You can go through a full implementation of that algorithm at another primesieve.
Here is, I believe, a working example of what you want:
function isPrime(num){
if(num < 2){
return false;
}
for(var i=2,l=Math.sqrt(num); i<=l; i++){
if(num % i === 0){
return false;
}
}
return true;
}
function range(f, t){
for(var i=f,r=[]; i<=t; i++){
r.push(i);
}
return r;
}
function primeRange(from, to){
var a = range(from, to), r = [];
for(var i=0,l=a.length; i<l; i++){
var v = a[i];
if(isPrime(v)){
r.push(v);
}
}
return r;
}
var prmRng = primeRange(1, 200);
console.log(prmRng);
I solved it this way:
let numbers = new Array();
for (let i = 1; i <= 200; i++) {
numbers.push(i);
}
let primeNumbers = (num) => {
let prime = new Array();
for(let i = 0; i < num.length; i++) {
let count = 0;
for (let p = 2; p <= num[i]; p++) {
if(num[i] % p === 0 && num[i] !== 2) {
count++;
} else {
if(num[i] === 2 || count === 0 && num[i]-1 === p) {
prime[i] = num[i];
}
}
}
}
return prime.filter(Boolean);
}
console.log(primeNumbers(numbers));