Advertisement
Fer22f

Prime factors

Jun 22nd, 2021
1,006
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // ==UserScript==
  2. // @name         Prime Factors
  3. // @namespace    http://tampermonkey.net/
  4. // @version      0.1
  5. // @description  try to take over the world!
  6. // @author       You
  7. // @match        https://duckduckgo.com/*
  8. // @grant        none
  9. // ==/UserScript==
  10.  
  11. (function() {
  12.     'use strict';
  13.  
  14.     function createElement(str) {
  15.         var frag = document.createDocumentFragment();
  16.         var elem = document.createElement('div');
  17.         elem.innerHTML = str;
  18.         while (elem.childNodes[0]) {
  19.             frag.appendChild(elem.childNodes[0]);
  20.         }
  21.         return frag;
  22.     }
  23.  
  24.     const searchInput = document.querySelector('#search_form_input');
  25.     if (searchInput && searchInput.value.startsWith('prime factors of')) {
  26.         const number = +searchInput.value.slice('prime factors of'.length);
  27.  
  28.         let n = number;
  29.         const primes = {};
  30.         for (let i = 2; i*i <= n; i++) {
  31.             while (n % i == 0) {
  32.                 if (primes[i] === undefined) { primes[i] = 0; }
  33.                 primes[i] += 1;
  34.                 n /= i;
  35.             }
  36.         }
  37.         if (n >= 0) {
  38.             if (primes[n] === undefined) { primes[n] = 0; }
  39.             primes[n] += 1;
  40.         }
  41.  
  42.         const headerWrapper = document.querySelector('#header_wrapper');
  43.         const el = createElement(`
  44.         <div id="zero_click_wrapper" class="zci-wrap">
  45.           <div class="zci  zci--factors is-active" id="zci-factors">
  46.             <div class="cw ">
  47.               <div class="zci__main  c-base">
  48.                 <div class="zci__body">
  49.                   <h3 class="c-base__title">${Object.entries(primes).map(([p, times]) => `${p}${times !== 1 ? `<sup>${times}</sup>` : ""}`).join(' &times; ')}</h3>
  50.                   <h4 class="c-base__sub">Prime Factors of: ${number}</h4>
  51.                   <div class="c-base__links"></div>
  52.                 </div>
  53.               </div>
  54.             </div>
  55.           </div>
  56.         </div>`)
  57.         headerWrapper.parentNode.insertBefore(el, headerWrapper.nextSibling);
  58.     }
  59. })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement