Factoring in Javascript

Asked

Viewed 1,844 times

4

How to factor numbers in this way ?

26 | 2
13 | 3
1  | 

Follow my code still incomplete: JSFIDDLE

  • You want prime factors or other factorization?

4 answers

4

NOTE: I don’t know if you set your example wrong, since 13 not and divisible by 3 or if that’s what you want it to be displayed. If it is comment I update my reply.

I will write in C, since I don’t know JS, but it must be good looking and, more important, simpler than the code you posted.

The first thing is that you will need a list of prime numbers to make the factorization. If you don’t have the list already in hand, you can use an algorithm to generate this list for you. A classic way, in the literal sense of the word, since it was "invented" by Erastosthenes some 2000 years ago, is as follows:

  1. We set a limit number to find cousins for him (N).
  2. We declare a list L containing N values true. That one list, at the end of the algorithm, will obey the following relationship:
    • If L[i] == true, if and only if i is a prime number.
  3. Now, we proceed as follows::
    • We marked L[0] and L[1] as false, since both 0 and 1 are not cousins.
    • From the i = 2, if i for primo (L[i] == true), we mark all its multiples as not cousins. I mean, we do L[2*i] = false, L[3*i] = false, etc..

That, in C, can stay like this:

#include <stdio.h>
#include <string.h>
#include <stdbool.h>

#define N 1000 /* Nosso limite */

bool L[N + 1];

void peneira() {
    /* Primeiro marcamos todos como true */
    memset(L, true, sizeof(L));

    /* Agora o 0 e o 1 não são primos */
    L[0] = L[1] = false;

    /* A parte mágica */
    for (int i = 2; i <= N; ++i) {
        if (L[i]) {
            /* Se i é um numero primo, seus múltiplos não são */
            for(int k = i + i; k <= N; k += i){
                L[k] = false;
            }
        }
    }
}

int main() {
    peneira();
    for (int i = 0; i < 30; ++i) {
        if (L[i]) {
            printf("%d e primo\n", i);
        }
    }
    return 0;
}

Running this, the exit and:

2 e primo
3 e primo
5 e primo
7 e primo
11 e primo
13 e primo
17 e primo
19 e primo
23 e primo
29 e primo

That is, all cousins up to 30.

Now that we’ve got all the cousins to our limit N, we can factor any number:

void fatora(int num) {
    /* Vou calcular o numero de digitos de num para imprimirmos
     * bonitinho como no seu exemplo */
     int tamanho = floor(log10(num)) + 1;
     int primo = 2;
     while (num > 1) {
         /* Enqto num e divisivel por primo */
         while (num % primo == 0) {
             printf("%*d | %d\n", tamanho, num, primo);
             num /= primo;
         }
         /* Agora vamos para o proximo primo */
         ++primo;
         while (L[primo] == false) {
             ++primo;
         }
     }
     /* Imprimimos a ultima linha */
     printf("%*d | \n", tamanho, 1);
}

Finally, if we turn

int main() {
    peneira();
    fatora(26);
    return 0;
}

The way out will be:

26 | 2
13 | 13
1  | 

4


Following the logic of factorization I arrived at this function:

function Calcular(nr) {
    var partes = [];
    while (nr > 1) {
        for (var i = 2; i <= nr; i++) {
            if (nr % i) continue;
            partes.push([nr, i]);
            nr = nr / i;
            break;
        }
    }
    partes.push([1, '']);
    return partes;
}

Some examples would be:

Calcular(4); // "[[4,2],[2,2],[1,""]]" 
Calcular(3); // "[[3,3],[1,""]]" 
Calcular(5); // "[[5,5],[1,""]]"
Calcular(6); // "[[6,2],[3,3],[1,""]]"
Calcular(8); // "[[8,2],[4,2],[2,2],[1,""]]" 

After mounting the HTML depends on how you want the final format. Assuming we use the same table here is a suggestion:

jsFiddle: http://jsfiddle.net/uLmxnm0q/

1

I found it on the Internet. I didn’t test it, but it seems to work:

function fator(numero) {
   if (isNaN(numero) || !isFinite(numero) || numero%1!=0 || numero==0) return ''+numero;
   if (numero<0) return '-'+fator(-numero);
   var minFator = lFator(numero);
   if (numero==minFator) return ''+numero;
   return minFator+'*'+fator(numero/minFator);
}

function lFator(numero) {
   if (isNaN(numero) || !isFinite(numero)) return NaN;  
   if (numero==0) return 0;  
   if (numero%1 || numero*numero<2) return 1;
   if (numero%2==0) return 2;  
   if (numero%3==0) return 3;  
   if (numero%5==0) return 5;  
   var m = Math.sqrt(numero);
   for (var i=7;i<=m;i+=30) {
      if (numero%i==0)      return i;
      if (numero%(i+4)==0)  return i+4;
      if (numero%(i+6)==0)  return i+6;
      if (numero%(i+10)==0) return i+10;
      if (numero%(i+12)==0) return i+12;
      if (numero%(i+16)==0) return i+16;
      if (numero%(i+22)==0) return i+22;
      if (numero%(i+24)==0) return i+24;
   }
   return numero;
}

Source: Javascriper

0

function fatoracao(aNumIn) {
var aRetorno = [
    [1, 1]
];
pFator = 1;
while (aNumIn != 1) {
    pFator++;
    pVezes = 0;
    while (aNumIn % pFator == 0) {
        pVezes += 1;
        aNumIn /= pFator;
    }
    if (pVezes) aRetorno.push([pFator, pVezes]);
}
return aRetorno;
}
let aIn = Math.pow(2, 5) * Math.pow(3, 2) * Math.pow(11, 1) * Math.pow(17, 2) * Math.pow(29, 1);
console.log(aIn, " >>>>  ", fatoracao(aIn));
// 26551008 ' >>>>  ' [ [ 1, 1 ], [ 2, 5 ], [ 3, 2 ], [ 11, 1 ], [ 17, 2 ], [ 29, 1 ] ]

Well, the above code returns a factored vector. Now you can format the output as you wish...

Browser other questions tagged

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