Advertisement
Guest User

Untitled

a guest
Dec 22nd, 2014
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. // Creating variables to use later
  2. var cORp;
  3. var primeNums = [];
  4. var compNums = [];
  5.  
  6. // Create numberSieve function
  7. function numberSieve(x) {
  8.  
  9. // 0 and 1 are not prime or composite
  10. if (x < 2 && x >= 0) {
  11. cORp = 'neither';
  12. }
  13.  
  14. // All negative numbers are composite
  15. else if (x < 0) {
  16. cORp = 'composite';
  17. }
  18.  
  19. // Sieve for positive numbers above 1
  20. else {
  21.  
  22. // Some more variables for later use
  23. possibleFactors = [];
  24. zFactors = [];
  25. matchingFactors = [];
  26.  
  27. // Takes all numbers that are half of x and below because they are possible factors
  28. for (i=2; i < x/2+1; i++) {
  29. possibleFactors.push(i);
  30. }
  31.  
  32. // Takes all possible factors and divides x by them
  33. for (i=0; i < possibleFactors.length; i++) {
  34. z = x/possibleFactors[i];
  35. zFactors.push(z);
  36. }
  37.  
  38. // Checks if the x divided by the possible factors is equal to any of the other possible factors
  39. for (i in possibleFactors) {
  40. if (zFactors.indexOf(possibleFactors[i]) !== -1) {
  41. matchingFactors.push(possibleFactors[i]);
  42. }
  43. }
  44.  
  45. // Checks if there are any matching factors
  46. if (matchingFactors.length !== 0) {
  47. cORp = 'composite';
  48. }
  49. else {
  50. cORp = 'prime';
  51. }
  52. }
  53.  
  54. // Prime numbers go to one array, Composite numbers go to another
  55. if (cORp === 'prime') {
  56. primeNums.push(x);
  57. }
  58. else if (cORp === 'composite') {
  59. compNums.push(x);
  60. }
  61. }
  62.  
  63. // For each number 0-100 runs the sieve
  64. a=0;
  65. while (a <= 100) {
  66. numberSieve(a);
  67. a++;
  68. }
  69.  
  70. // Prints out the prime number and composite number arrays
  71. console.log("Prime Numbers: " + primeNums);
  72. console.log("Composite Numbers: " + compNums);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement