Prime number factorization - javascript

I'm trying to write a function to take a positive integer and a prime number as an input and return true if the prime factors of the given positive integer are less than or equal the given prime number.
Given prime number should be a prime factor of the given positive integer.
hasLessPrimeFactor(20,5) should return true because Prime Factors of a Number: 20 = 2 X 2 X 5
Up to now I have completed 3 test cases out of 4 test cases
The return type should be a string.
hasLessPrimeFactor(20,5) should return true
hasLessPrimeFactor(20,7) should return false
The answer should be valid for any given input.(above mentioned not passed test case)
What I've done so far :
function hasLessPrimeFactor(num,primenum){
let arr = [];
if(num < 2 || primenum < 2 || isNaN(num) ||isNaN(primenum)){
return 0;
}
for (i = 2; i <= num; i++) {
while ((num % i) === 0) {
arr.push(i);
num /= i;
}
}
for (var k = 0; k < arr.length; k++) {
if(arr[k] == primenum && arr.length <= primenum)
return true;
}
return false;
}
hasLessPrimeFactor(20,5);
Any suggestion is welcome.

Given the requirement gleaned from your comment that the primenum variable should be a factor of num, you could verify that at the beginning. It seems a strange requirement, though-- not really implied in the name of the method, so I'd look closely to make sure you didn't introduce any accidental assumptions. That said, this would test to ensure the primenum parameter is a factor of num.
if (num % primenum) return false;
Additionally, your first for loop need not iterate from 2..num; it would be sufficient to iterate from 2..primenum.

Related

how to make a script to print out all prime numbers in js

I want to know how I can improve my code by helping it find out what number is prime and what is not. I was thinking that I would divide a number by a number and then if it is a decimal number then it is prime,
I want it to have a loop to check every number 1 to 100 and see if it is a prime number
This is what I have so far:
for(let i = 1; i <= 100; i++) {
if(i == 1) {
}else if(i == 2) {
console.log(`${i} is a prime number`);
}else if(i >= 3){
x = i / 2;
tf = Number.isInteger(x);
if(tf == false && i >= 3) {
console.log(`${i} is a prime number`);
}
}
}
and so far it outputs 1 2 and all the odd numbers.
Create a function to test whether a number is prime or not (divisible only by 1 and itself). Then call this function inside the loop on each number.
function isPrimeNumber(no) {
if (no < 2) {
return false;
}
for (let i = 2; i < no; i++) {
if (no % i == 0) {
return false;
}
}
return true;
}
for (let i = 1; i <= 100; i++) {
if (isPrimeNumber(i)) {
console.log(i);
}
}
var numbers = new Array(101).fill(0).map((it, index) => index);
var halfWay = Math.floor(numbers.length / 2);
for (let i = 2; i <= halfWay; i++) {
if (!numbers[i]) continue;
for (let j = 2; j * i < numbers.length; j++) {
console.log(`${i} * ${j} = ${i * j}`);
numbers[j * i] = null;
}
}
console.log(numbers.filter(it => it));
Here is an attempt to mathematically find numbers between 1-100 that are primes.
Fill an array of numbers 0-100
For every number (starting at 2), multiply it by itself and all numbers after it, up to half of the array
For every computed number, remore it from the array, as it is not a prime
At the end, filter out all numbers that are null
As Taplar stated primes are numbers that only divide by the number itself and 1.
As far as improving your code. I would say you want to eliminate as many possible numbers with the fewest questions.
An example would be is the number even and not 2 if so it is not prime? The interesting part of this question you eliminate dividing by all even numbers as well. This instantly answers half of all possible numbers and halves the seek time with the ones you need to lookup.
So what would this look like?
function isPrime(num) {
// Check it the number is 1 or 2
if (num === 1 || num === 2) {
return true
}
// Check if the number is even
else if (num % 2 === 0) {
return false;
}
// Look it up
else {
// Skip 1 and 2 and start with 3 and skip all even numbers as they have already been checked
for (let i = 3; i <= num/2; i+=2) {
// If it divides correctly then it is not Prime
if (num % i === 0) {
return false
}
}
// Found no numbers that divide evenly it is Prime
return true
}
}
console.log('1:', isPrime(1))
console.log('2:', isPrime(2))
console.log('3:', isPrime(3))
console.log('4:', isPrime(4))
console.log('11:', isPrime(11))
console.log('12:', isPrime(12))
console.log('97:', isPrime(97))
console.log('99:', isPrime(99))
console.log('65727:', isPrime(65727))
console.log('65729:', isPrime(65729))

Creating a For loop to find sum of proper divisors

I have this problem for my CIS class: "Write a function named sumOfProperDivisors that accepts an integer n > 1, and returns the sum of the proper divisors of n.(A proper divisor is a positive divisor of a number, excluding the number itself. For example, 1, 2, and 3 are proper divisors of 6, but 6 itself is not.) Use a for loop, and use function expression syntax."
I don't even know where to start. This is all I have so far and I'm pretty sure it's completely wrong. PLEASE I NEED HELP
var sumOfProperDivisors = function(n > 1) {
let sum = 0;
for (var i = 1; i <= n; i++)
// we don't have to search all numbers from 2 to the integer part of n / 2,
// but from 2 to the integer part of the square root of n
// if n = 1000 we look for divisors in the interval [2, 31] and not in [2, 500]
const sumOfProperDivisors = n => {
const root = Math.sqrt(n);
let result = 1 + Number.isInteger(root) * root;
for (let k = 2; k < root; k++) {
if (n % k === 0) result += k + n / k;
}
return result;
}
console.log(sumOfProperDivisors(6));
console.log(sumOfProperDivisors(1000));
console.log(sumOfProperDivisors(1000000));
Welcome to Stack Overflow
Read about asking homework questions - How do I ask and answer homework questions?
Also, read about asking a good question - https://stackoverflow.com/help/how-to-ask
The answer:
You can do it like this:
loop over from i = 1 to i = n/2 because once it cannot be divisible by something greater and n/2 and n.
if the modulo (remainder) of n / i is zero then increment sum
return sum
function sumOfProperDivisors(n) {
let sum = 0;
for (var i = 1; i <= n/2; i++){
if (n % i == 0){
sum++;
}
}
return sum;
}
console.log(sumOfProperDivisors(6))
The laziest way to do this is loop through all the numbers before n, 1 to n-1
and check if the modulo of n with the number gives 0 that means n is divisible by that number then add that number to a variable "sum" each time the condition applies.
You can alter some details like looping from 1 to n/2 to remove unnecessary numbers.
When you define a function, what goes in the parenthesis is the name of the argument, possibly with a default argument value, but the > 1 syntax you're using is not valid.
So, instead of:
function (n>1) {...}
You would need to do something like:
function (n) {
if (n <= 1) {
// ... throw an error or something...
// or maybe you don't need to bother with this?
// it's not super clear to me from the assignment
}
The other thing I would point you to in order to answer your question is the modulo operator, which is the percent sign (%) in javascript. That operator will return the remainder of a division operator, so if you want to check if a number is divisible by another number, you can check if the remainder is 0 in this way...
if (3 % 2 === 0) { console.log('3 is divisible by 2')}
if (4 % 2 === 0) { console.log('4 is divisible by 2')}
if (5 % 2 === 0) { console.log('5 is divisible by 2')}
One final note: it's nice to write a bunch of tests for yourself to see how your function works and see if you understand it. So if I got this problem as homework, the first thing I might do is write a bunch of statements to test out my answer and see how they work...
For example:
console.log('sumOfProperDivisors(4) should be 3... and it is ',sumOfProperDivisors(4))
console.log('sumOfProperDivisors(5) should be 1... and it is ',sumOfProperDivisors(5))
console.log('sumOfProperDivisors(6) should be 6... and it is ',sumOfProperDivisors(6))
console.log('sumOfProperDivisors(8) should be 7... and it is ',sumOfProperDivisors(8))
function findProperDivisor(num) {
if(num<0) return
let sum = 0;
for (let i = 0; i < Math.floor(num / 2); i++) {
if (num % i === 0) {
sum += i;
}
}
return sum
}

Why does the 'if' condition here works?

The code here check for prime numbers from 2 to n:
<script>
function showPrimes(n) {
for (let i = 2; i < n; i++) {
if (!isPrime(i)) continue;
alert(i); // a prime
}
}
function isPrime(n) {
for (let i = 2; i < n; i++) {
if ( n % i == 0) return false;
}
return true;
}
</script>
But I don't understand why it works for number 2 and return false when both n and i equal to 2 while it doesn't happen with other prime numbers. I am new to javascript(and programming in general) and from what I understood this code take the i from the first iteration in the first loop(on the "showPrimes" function) and put it on "isPrime" function as a parameter and in that function it becomes the "n" in the 'if' condition and it checks if there is a remainder when it gets divided by the i from the loop of "isPrime" so (n % i == 0) should be (2 % 2 == 0) in the first iteration, Is that right? if so why does it works just like it work for other prime numbers which clearly become false unlike (2 % 2 == 0) which is true...
What I am missing here?. Sorry if this is an obvious/stupid question, it is the first time I am learning anything related to programming.
function isPrime(n) {
for (let i = 2; i < n; i++) {
When n=2; i=2; The above loop will not be entered.

What is the time complexity of my code?

So I just started studying the Big O notation on my own. I thought I had understood the basics till I wrote a function to check for prime numbers and tried to figure out its time complexity. Here's the code:
function isPrime(num){
if (num === 1 || num%1 !== 0){ //Checks if num is 1 or decimal
return false;
}
else{
for (var i = 2; i < num; i++) {
if (num%i === 0 && i!== 1){ //Checks if any numbers from 2 to are divisible by num
return false
}
}
}
return true;
}
console.log(isPrime(6));
First thing that confused me is whether multiple conditions inside an if statement make any difference or it is just counted once? And then notice I have three return statements. Does that mean I have to include that last line of code where I pass a number to the function to evaluate its time-complexity? Or can I do it without a passed value and calculate for different cases?
function isPrime(n){
if (n === 1 || n%1 !== 0){ //Checks if num is 1 or decimal
return false;
}
for (var i = 2; i < n; i++) {
if (n%i === 0){
return false
}
}
return true;
}
I have made some small refactoring which doesn't change the complexity but makes the code more readable for struggling with Big-O.
So for n > 1, n : orime, the number of operations is:
So the complexity of your algorithm is O(n).

Function to determine largest prime factor

I am trying to write a function in JS that returns a number's maximum "prime" factor. For example, if I ran maxPrimeFactor(57), I should return a 19. However, my function only works part of the time. I have written a helper function called isPrime that returns a boolean that indicates whether a given number is prime.
Can anyone spot-check my logic and give me pointers as to where I may be going wrong/how I can improve my algorithm and implementation? Any help is appreciated.
function isPrime(n){
var flag = true;
for (var i = 2; i < n / 2; i++) {
if (n % i == 0) {
flag = false;
return flag;
}
}
return flag;
}
function maxPrimeFactor (n) {
var max = 1;
for (var i = 1; i <= n/2; i++) {
if (n % i == 0 && isPrime(i)) {
max = i;
}
}
return max;
}
1 is not prime, so if you pass 1 to the function it will return 1 as the max prime factor which is incorrect. Perhaps a check returning a value like NaN or undefined may be helpful to prevent invalid values, this depends on if you need to limit the scope of the inputs.
if (n < 2) {
return NaN;
}
You also need to consider the case for when n is prime. A possible way around this more efficiently would be to initialize max to n, and then if max is never set again, the max prime is n.
function maxPrimeFactor (n) {
var max = n;
for (var i = 2; i <= n/2; i++) {
if (n % i == 0 && isPrime(i)) {
max = i;
}
}
return max;
}
Since the algorithm only cares about the greatest prime factor, if you start counting down from n/2, you can further optimize the function to return the first prime factor that is found, otherwise return the number.
As the local var flag in isPrime() isn't making the code more readable or functional I would remove it . (Also, no need to loop to n/2 as no number has a prime greater than it's square root);
function isPrime(n){
for (var i = 2; i < Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
I give U a code written in C++ below:
#include <cstdio>
#include <cmath>
int max(int x, int y)
{
return x > y ? x : y;
}
int maxPrime(int x)
{
int mx = -1;
int curX = x;
/*i * i <= x is correct, because there is only one prime factor larger than
Sqrt(x), it's power must be 1, and actually it is curX after this loop, because
all prime factor less or equal than Sqrt(x) is eliminated.*/
for(int i = 2; i * i <= x; ++i)
{
while(curX % i == 0)
{
/*Here i must be a prime. consider Prime factorization
x = p1^q1 * p2^q2 * p3^q3...(p1<p2<p3...)
the first number that satisfied x % i == 0 must be p1, it's prime!
and p2 > p1 so I can continue to enumerate i, don't need to reset i to 2.
curX = x/(p1^q1 * p2^q2 * ... * pj^qj) and i = p[j+1]
*/
curX /= i, mx = max(i, mx);
}
}
return max(mx, curX);
}
int main()
{
int n;
scanf("%d", &n);
//I suppose n is positive
if(n == 1) //1 is not prime
printf("No solution\n");
else
printf("%d\n", maxPrime(n));
return 0;
}
This code reaches a worst case running time O(Sqrt(n))
And your code is wrong, because when n is a prime, your code cannot get the right answer.
And your code's efficiency is not good.
If you want a faster code, you can learn Pollard Rho or SQUFOF.

Categories

Resources