Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Creating variables to use later
- var cORp;
- var primeNums = [];
- var compNums = [];
- // Create numberSieve function
- function numberSieve(x) {
- // 0 and 1 are not prime or composite
- if (x < 2 && x >= 0) {
- cORp = 'neither';
- }
- // All negative numbers are composite
- else if (x < 0) {
- cORp = 'composite';
- }
- // Sieve for positive numbers above 1
- else {
- // Some more variables for later use
- possibleFactors = [];
- zFactors = [];
- matchingFactors = [];
- // Takes all numbers that are half of x and below because they are possible factors
- for (i=2; i < x/2+1; i++) {
- possibleFactors.push(i);
- }
- // Takes all possible factors and divides x by them
- for (i=0; i < possibleFactors.length; i++) {
- z = x/possibleFactors[i];
- zFactors.push(z);
- }
- // Checks if the x divided by the possible factors is equal to any of the other possible factors
- for (i in possibleFactors) {
- if (zFactors.indexOf(possibleFactors[i]) !== -1) {
- matchingFactors.push(possibleFactors[i]);
- }
- }
- // Checks if there are any matching factors
- if (matchingFactors.length !== 0) {
- cORp = 'composite';
- }
- else {
- cORp = 'prime';
- }
- }
- // Prime numbers go to one array, Composite numbers go to another
- if (cORp === 'prime') {
- primeNums.push(x);
- }
- else if (cORp === 'composite') {
- compNums.push(x);
- }
- }
- // For each number 0-100 runs the sieve
- a=0;
- while (a <= 100) {
- numberSieve(a);
- a++;
- }
- // Prints out the prime number and composite number arrays
- console.log("Prime Numbers: " + primeNums);
- console.log("Composite Numbers: " + compNums);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement