20-CS-122-001 Computer Science II Spring 2012
Hamming: Generate and Test (slow)

Virtual functions, classes, inheritance, lists, queues, stacks, applications

Prev      Next      Lectures      Source

/* Go through all prime factors of all numbers.  If
// a number has all prime factors in given list of primes
// then output the number, otherwise forget it.
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
using namespace std;

#define N 10
/* Use define to make changing the variable size easy */
typedef long long reallong;

int main(int argc, char **argv) {
   int p[N];	   /* Array of primes */
   reallong c,i;   /* Possibilities */
   int k,q,n;      /* temp variables */

   /* Primes must be ordered smallest to largest */
   n = argc;
   for (k=1 ; k < n ; k++) p[k-1] = atoi(argv[k]);
   cout << "\nPrime List:";
   for (k=0 ; k < n-1 ; k++) cout << " " << p[k];
   cout << "\n";

   /* Here is the fun part */
   q = 1;
   for (i=2 ; ; i++) {
      c = i;
      for (k=0 ; k < n && c != 1 ; k++)
         while((c % p[k]) == 0 && c != 1 && p[k] <= c) c = c / p[k];
      if (c == 1) cout << q++ << ":\t" << i << "\n";
   }
   return 0;
}