Reorganizig code on sieve of Eratosthenes

I need help on reorgaizing my code.
import java.io.*;
import java.text.DecimalFormat;
public class sieve
     public static void main(String args[]) throws IOException
                    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
          System.out.print("Enter the primes upper bound  ===>>  ");
          int MAX = Integer.parseInt(input.readLine());
          double sqrt=0;
          MAX++;
          boolean primes[] = new boolean[MAX];
          computePrimes(primes);
          displayPrimes(primes);
          System.out.println();
     public static void computePrimes(boolean [] primes)
          System.out.println();
          System.out.println("Computing prime numbers\t");
          System.out.println();
          int MAX=primes.length;
          double sqrt=Math.sqrt(MAX);
          for(int i = 2; i < MAX; i++)
               primes[i] = true;
          for(int i = 2; i <= sqrt; i++)
               for(int j = i*2; j < MAX; j+=i)
                    primes[j] = false;
     public static void displayPrimes(boolean [] primes)
     DecimalFormat threeDigits= new DecimalFormat("000");
     final int MAX=primes.length;
     int r=MAX-1;
     System.out.println("\n Prime numbers between 1 and " + r + "\n");
          for(int i = 0; i < primes.length; i++)
               if(primes)
                    System.out.print(threeDigits.format(i) + "\t");
For the main method heading, it is supposed to go like:
public static void main(String args[]) throws IOException
                    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
          System.out.print("Enter the primes upper bound  ===>>  ");
          final int MAX = Integer.parseInt(input.readLine());
          boolean primes[] = new boolean[MAX];
          computePrimes(primes);
          displayPrimes(primes);
I'm not supposed to add anything to the main method heading, but if I don't my code doesn't work. Could somebody advise me on how I should reorganize my code, but still keep the general format? Thank you!

You don't need sqrt in main. It's never used.
And you don't need MAX++. I assume MAX is the highest number to test.
Lets say MAX is 5, and we create an array of 5 elements. Their indices are 0, 1, 2, 3, 4. Well, zero isn't even a candidate for being a prime. (Neither is 1, for that matter.) So we can put the results for 1 into slot 0, etc. up to results for 5 into slot 4.
And you don't need the System.out.println in main. If you want to print an extra line, do it in the display method.
Is that what you mean? If not, please clarify. "Doesn't work" carries zero information, or near enough as makes no difference.

Similar Messages

  • Who can help rewrite code

    I use wordpress made a website, http://www.beijing-tour-service.com but can not change the footer link. Is There any one can help?   the code is :
    <div class="span-24">
            <div id="footer">Copyright &copy; <a href="<?php bloginfo('home'); ?>"><strong><?php bloginfo('name'); ?></strong></a>  - <?php bloginfo('description'); ?></div>
            <?php // This theme is released free for use under creative commons licence. http://creativecommons.org/licenses/by/3.0/
                // All links in the footer should remain intact.
                // These links are all family friendly and will not hurt your site in any way.
                // Warning! Your site may stop working if these links are edited or deleted  ?>
            <div id="footer2">Powered by <a href="http://wordpress.org/"><strong>WordPress</strong></a> | Buy <a href="http://www.bestincellphones.com" title="Free CellPhones">Free Cell Phones</a> Online. | Thanks to <a href="http://www.bromoney.com/cd-rates">CD</a>, <a href="http://www.bromoney.com/savings-account-interest-rates">Savings Account</a> and <a href="http://fatburningrules.com">Fat burning Furnace</a></div>
        </div>
    </div>
    </div>
    <?php
         wp_footer();
        echo get_theme_option("footer")  . "\n";
    ?>
    </body>
    </html>

    Looks like The Sieve of Eratosthenes.
    A google search for that should help you with some logic.
    Wikipedia has a really nice animation of how it works.
    Post back when you have some source code that you need help with.
    Thanks k???? lullzz???

  • Who can help me? write this code?

    Write java code print prime number like this
    Sample Screen Print:
    Initial matrix with N = 37
    2 3 4 5 6 7 8 9 10
    11 12 13 14 15 16 17 18 19 20
    21 22 23 24 25 26 27 28 29 30
    31 32 33 34 35 36 37
    Intermediate results (after 1st iteration)
    2 3 5 7 9
    11 13 15 17 19
    21 23 25 27 29
    31 33 35 37
    Intermediate results (after 2nd iteration)
    2 3 5 7
    11 13 17 19
    23 25 29
    31 35 37
    Intermediate results (after 7th iteration)
    2 3 5 7
    11 13 17 19
    23 29
    31 37
    Final results
    2 3 5 7 11 13 17 19 23 29
    31 37
    How to write this code ?
    Please Help me!
    Thank you so muchhh ?????

    Looks like The Sieve of Eratosthenes.
    A google search for that should help you with some logic.
    Wikipedia has a really nice animation of how it works.
    Post back when you have some source code that you need help with.
    Thanks k???? lullzz???

  • Problem with constructors and using public classes

    Hi, I'm totally new to Java and I'm having a lot of problems with my program :(
    I have to create constructor which creates bool's array of adequate size to create a sieve of Eratosthenes (for 2 ->n).
    Then it has to create public method boolean prime(m) which returs true if the given number is prime and false if it's not prime.
    And then I have to create class with main function which chooses from the given arguments the maximum and creates for it the sieve
    (using the class which was created before) and returns if the arguments are prime or not.
    This is what I've written but of course it's messy and it doesn't work. Can anyone help with that?
    //part with a constructor
    public class ESieve {
      ESieve(int n) {
    boolean[] isPrime = new boolean[n+1];
    for (int i=2; i<=n; i++)
    isPrime=true;
    for(int i=2;i*i<n;i++){
    if(isPrime[i]){
    for(int j=i;i*j<=n;j++){
    isPrime[i*j]=false;}}}
    public static boolean Prime(int m)
    for(int i=0; i<=m; i++)
    if (isPrime[i]<2) return false;
    try
    m=Integer.parseInt(args[i]);
    catch (NumberFormatException ex)
    System.out.println(args[i] + " is not an integer");
    continue;
    if (isPrime[i]=true)
    System.out.println (isPrime[i] + " is prime");
    else
    System.out.println (isPrime[i] + " is not prime");
    //main
    public class ESieveTest{
    public static void main (String args[])
    public static int max(int[] args) {
    int maximum = args[0];
    for (int i=1; i<args.length; i++) {
    if (args[i] > maximum) {
    maximum = args[i];
    return maximum;
    new ESieve(maximum);
    for(int i=0; i<args.length; i++)
    Prime(i);}

    I've made changes and now my code looks like this:
    public class ESieve {
      ESieve(int n) {
       sieve(n);
    public static boolean sieve(int n)
         boolean[] s = new boolean[n+1];
         for (int i=2; i<=n; i++)
    s=true;
    for(int i=2;i*i<n;i++){
    if(s[i]){
    for(int j=i;i*j<=n;j++){
    s[i*j]=false;}}}
    return s[n];}
    public static boolean prime(int m)
    if (m<2) return false;
    boolean x = sieve(m);
    if (x=true)
    System.out.println (m + " is prime");
    else
    System.out.println (m + " is not prime");
    return x;}
    //main
    public class ESieveTest{
    public static int max(int[] args) {
    int maximum = args[0];
    for (int i=1; i<args.length; i++) {
    if (args[i] > maximum) {
    maximum = args[i];
    return maximum;
    public static void main (String[] args)
    int n; int i, j;
    for(i=0;i<=args.length;i++)
    n=Integer.parseInt(args[i]);
    int maximum=max(args[]);
    ESieve S = new ESieve(maximum);
    for(i=0; i<args.length; i++)
    S.prime(i);}
    It shows an error for main:
    {quote} ESieveTest.java:21: '.class' expected
    int maximum=max(args[]); {quote}
    Any suggestions how to fix it?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Problem With File Reading And Sorting

    I'm having problems with a particular task. Here is what I have to do:
    Write a program which reads 100 integers from a file. Store these integers
    in an array in the order in whcih they are read. Print them to the screen.
    Sort the integers in place using bubble sort. Print the sorted array to the
    screen. Now implement the sieve of Eratosthenes to place all prime numbers
    in an ArrayList. Print that list to the screen.
    Here is the code I have so far:
    import java.util.ArrayList;
    import java.io.*;
    public class Eratosthenes
        private ArrayList numbers;
        private String inputfile1 = "numbers.txt";
        public Eratosthenes()
            numbers = new ArrayList();
        public void readData()
            try {
                BufferedReader reader = new BufferedReader(new FileReader(inputfile1));
                for(int i = 1; i <= 100; i++) {
                    String temp = reader.readLine();
                    numbers.add();
            catch(Exception e)
    This is the file reading part I have done but it doesn't recognise the line numbers.add() . It brings up the error - 'Cannot resolve symbol - method add(). Thats the first problem I have, can anyone see any way to fix it and to achieve the task. Also can someone help with the structure of a bubble sort method and a sieve of Eratosthenes method as I have no clue whatsoever. Any help will be greatly appreciated.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Ok, I've done that but I'm having another problem. When I'm printing an output to the screen, it prints 100 lines of integers and not 1 line of 100 integers. Can you see the problem in the code that is doing this?
    import java.util.ArrayList;
    import java.io.*;
    public class Eratosthenes
        private ArrayList numbers;
        private String inputfile1 = "numbers.txt";
        public Eratosthenes()
            numbers = new ArrayList();
        public void readData()
            try {
                BufferedReader reader = new BufferedReader(new FileReader(inputfile1));
                for(int i = 1; i <= 100; i++) {
                    String temp = reader.readLine();
                    numbers.add(temp);
                    System.out.println(numbers);
            catch(Exception e)
    }

  • [RESOLVED] How I pass in my command-line variables disgusts me

    Hello,
    What I'm trying to do is to make an easily configurable script that the user can run with just a few basic command line variables (some of our users are not programmers.)  Now, here's my problem, when it comes to extracting the variables from the command line, it's kind of messy.  Lets say I have the following command:
    $ ./hl_script.sh --config-file=config_abc.txt --rate=5000 --data-dump=/opt/dump_area -v
    "-v" means verbose
    Now, given the weird arrangement of the different types of command line arguments, I'd like to extract the salient parts of the information that I care about.  However, at this moment, all I have is the "cut" command which can easily get into undefined behavior territory should the user misstype an input.  I would love to know how you have done this and what your approach to this problem is.
    This is the code that I have so far:
    # this is where we run the initial test and check if the user entered the
    # help flag in order to see how to properly use this application.
    if [ $# -gt 1 ]; then
    for argument in $@
    do
    if [ $argument = "--help" ]; then
    echo "Here is how you would use this software and the flags that would"
    echo " be useful."
    echo " --help"
    echo " Brings up this display and shows a listing of the options"
    echo " that can be used to better utilize this app."
    echo ""
    echo " --config-file=N"
    echo " Specify the config file that we'd like to use."
    echo ""
    exit 0
    elif [ `cut $argument | cut -d'=' -f 1` = "--config-file" ]; then
    # read-in the config file that we specified and then proceed to set a
    # bunch of environment variables that we need.
    echo "stuff..."
    fi
    done
    fi
    Last edited by publicus (2014-05-13 13:13:43)

    ewaller wrote:
    I know your sample code is Bash, but you may want to consider doing it in Python and using this library
    Here is a simple Python program I wrote that uses the library:
    ewaller$@$odin ~/devel/python 1004 %./sieve.py
    Usage: sieve.py [options] arg
    sieve.py: error: incorrect number of arguments
    ewaller$@$odin ~/devel/python [2]1005 %./sieve.py 10
    2 3 5 7
    ewaller$@$odin ~/devel/python 1006 %./sieve.py --help
    Usage: sieve.py [options] arg
    Find prime numbers using a sieve of Eratosthenes
    Options:
    -h, --help show this help message and exit
    -v, --verbose
    ewaller$@$odin ~/devel/python 1007 %./sieve.py 10 -v
    removing 4
    removing 6
    removing 8
    removing 10
    removing 6
    removing 9
    removing 10
    2 3 5 7
    ewaller$@$odin ~/devel/python 1008 %cat sieve.py
    #! /usr/bin/python
    Implement a sieve of Eratosthenes
    from optparse import OptionParser
    def main():
    #Handle all the command line nonsense. We need a number as an argument
    usage = "%prog [options] arg"
    description = "Find prime numbers using a sieve of Eratosthenes"
    parser = OptionParser(usage=usage,description=description)
    parser.add_option("-v", "--verbose", action="store_true", dest="verbose")
    (options, args) = parser.parse_args()
    if len(args) != 1:
    parser.error("incorrect number of arguments")
    try:
    maxval=eval(args[0])
    except:
    parser.error ("Argument is not a number")
    # Here is the sieve
    a=[x for x in range(0,maxval+1)]
    for count in range(2,int(maxval/2)+1):
    if a[count]:
    for i in range(count*2,maxval+1,count):
    a[i]=0
    if options.verbose:
    print ("removing %i"%i)
    # and report the results
    wrap=0
    for count in range(2,len(a)):
    if a[count]:
    print (count,end=" ")
    wrap += 1
    if (wrap == 5):
    print()
    wrap = 0
    print ()
    if __name__ == "__main__":
    main()
    ewaller$@$odin ~/devel/python 1009 %
    The thing is, I already have some shell code written that works, so I don't want to re-write (and re-test) that.

  • Big-OH and Big-Omega question?

    I am looking for some inputs regarding Big-OH and Big_Omega of a method that I wrote. This method implements queue data structure and its purpose is to find primes of a number using Sieve of Eratosthenes. I am thinking it is a Big-Oh of N^2 (upper bound), since it is a nested while loop, but I am not sure of the lower bound, which Big_Omega. Any comments guys? Thanks
    public static void printAllPrimes(int max)
              LinkedQueue qNum = new LinkedQueue();     //list of numbers
              LinkedQueue qPrime = new LinkedQueue();     //list of primes
              LinkedQueue qTemp = new LinkedQueue();     //temporary list of numbers
              Integer object = new Integer(0);          //prime number
              Integer temp; //temp holder for comparison                                   
              //copy all numbers to qNum beginning with 2.
              for(int i = 2; i<=max; i++)
                   Integer num = new Integer(i);
                   qNum.enqueue(num);
              //checking for multiples of next prime until qNUm is empty
              do
                   //remove next prime from qNum and store it to qPrime
                   object = (Integer)(qNum.dequeue());
                   qPrime.enqueue(object);
                   //check for multiples of a next prime value
                   while(!qNum.isEmpty())
                        temp = (Integer)(qNum.first());
                        if((temp.intValue() % object.intValue() == 0))
                             qNum.dequeue();
                        else
                             qTemp.enqueue(qNum.dequeue());
                   //copy the content of qTemp to qNum
                   while(!qTemp.isEmpty())
                        qNum.enqueue(qTemp.dequeue());
              }while(!qNum.isEmpty());
              //print primes of number
              System.out.println("********** Primes of " + max + " **********");
              while(!qPrime.isEmpty())
                   System.out.print(qPrime.dequeue() + " ");
              System.out.println();

    Use &#91;code]&#91;/code] tags, and you can get much more legible code: public static void printAllPrimes(int max)
        LinkedQueue qNum = new LinkedQueue(); //list of numbers
        LinkedQueue qPrime = new LinkedQueue(); //list of primes
        LinkedQueue qTemp = new LinkedQueue(); //temporary list of numbers
        Integer object = new Integer(0); //prime number
        Integer temp; //temp holder for comparison
        //copy all numbers to qNum beginning with 2.
        for(int i = 2; i<=max; i++)
            Integer num = new Integer(i);
            qNum.enqueue(num);
        //checking for multiples of next prime until qNUm is empty
        do
            //remove next prime from qNum and store it to qPrime
            object = (Integer)(qNum.dequeue());
            qPrime.enqueue(object);
            //check for multiples of a next prime value
            while(!qNum.isEmpty())
                temp = (Integer)(qNum.first());
                if((temp.intValue() % object.intValue() == 0))
                    qNum.dequeue();
                else
                    qTemp.enqueue(qNum.dequeue());
            //copy the content of qTemp to qNum
            while(!qTemp.isEmpty())
                qNum.enqueue(qTemp.dequeue());
        }while(!qNum.isEmpty());
        //print primes of number
        System.out.println("********** Primes of " + max + " **********");
        while(!qPrime.isEmpty())
            System.out.print(qPrime.dequeue() + " ");
        System.out.println();
    }

  • Why is kernel-2.6.9 (OEL-4) faster than kernel-2.6.18 (OEL-5) ?

    Hi,
    as long as RHEL-5 and then OEL-5 have been released, I have been wondering why my own programs, compiled and run on RHEL-5/OEL-5, are slower than the same programs compiled and run on RHEL-4/OEL-4 on the same machine. This is really barmy since gcc-4.1, shipped with RHEL-5/OEL-5, is very aggressive compiler and produces faster binary code than gcc-3.4.6, shipped with RHEL-4/OEL-4. I verified this hundred times testing both compilers on RHEL-4/OEL-4 and RHEL-5/OEL-5. The 4.1 compiler always produces faster executable on the same OS.
    The problem is obviously in kernel-2.6.18. There is something in the kernel (maybe scheduler?) that slows down the execution of programs. But what? I experimented with changing various kernel boot parameters (eg "acpi=off" etc), even tried to recompile the kernel many times with various combinations of config parameters, and nothing helps. Thus, I'm still wondering whether the problem is solvable by disabling one or more config parameters and recompiling the kernel, or is deeply embedded in the main kernel code.
    Is there anybody in this forum who experienced the same, say running OEL-4 before migrating to OEL-5?
    Here are two examples showing different execution times on OEL-4.5 (kernel-2.6.9-55.0.5.0.1.EL.i686, gcc-3.4.6-8.0.1) and OEL-5 (kernel-2.6.18-8.1.10.0.1.el5, gcc-4.1.1-52.el5.2). The first example is trivial but very sensitive to overal system load and kernel version. The second example is "Sieve of Eratosthenes" - the program for finding prime numbers (CPU bound).
    EXAMPLE 1.
    /*  Simle program for text screen console  */
    /*  very sensitive to overall system load  */
    /*  and kernel version                     */
    #include <stdio.h>
    int main(void)
        register int i;
        for(i = 0; i < 1000000; i++)
         printf(" %d ", i);
        return 0;
    /* end of program */
    $ gcc -O2 -o example1 -s example1.c
    $ time ./example1The average execution times on OEL-4.5 and OEL-5 are as follow:
    Mode      OEL-4.5         OEL-5
    real      0m3.141s        0m4.931s
    user      0m0.394s        0m0.366s
    sys       0m2.747s        0m4.563s
    ----------------------------------As we can see, the program on the same machine, compiled and run on OEL-4.5 (gcc-3.4.6 and kernel-2.6.9) is 57% faster than the same program compiled and run on OEL-5 (gcc-4.1.1 and kernel-2.6.18), although gcc-4.1.1 produces much faster binary code. Since the times the process spent in user mode are almost equal on both OS, the whole difference is due to the time the process spent in kernel mode. Note that kernel mode (sys) is taking 66% more time on OEL-5. It tells me that "something" in the kernel-2.6.18 slows down the execution of the program.
    In the second example OEL-4.5 is also faster than OEL-5, but the differences in execution times are not so drastic as in the first example.
    EXAMPLE 2.
    /*           Sieve of Eratosthenes           */
    #define GNUSOURCE
    #include <stdio.h>
    #include <stdlib.h>
    #define MAX_PRIME_AREA 100000
    #define REPEAT_LOOP 10000
    int main(void)
        int prime, composite, count;
        char *sieve_array;
        if ((sieve_array = (char *) malloc( (size_t) (MAX_PRIME_AREA + 1))) == NULL)
         fprintf(stderr,"Memory block too big!\nMemory allocation failed!\a\n");
         exit(EXIT_FAILURE);
        for(count = 0; count < REPEAT_LOOP; count++)
         for(prime = 0; prime < (MAX_PRIME_AREA + 1); prime++)
                 *(sieve_array + prime) = (char) '\0';
         for(prime = 3; prime < (MAX_PRIME_AREA + 1); prime += 2)
             if (! *(sieve_array + prime) )
              *(sieve_array + prime) = (char) 'P';  /* offset prime is a prime */
                 for(composite = (2 * prime); composite < (MAX_PRIME_AREA + 1); composite += prime)
                  *(sieve_array + composite) = (char) 'X';  /* offset composite is a composite */
            /* DO NOT COMPILE FOR TEST !!!
            fprintf(stdout, "\n%d\n", 2);
            for(prime = 3; prime < (MAX_PRIME_AREA + 1); prime += 2)
                if ( *(sieve_array + prime) == 'P' )
                    fprintf(stdout, "%d\n", prime);
        free(sieve_array);     
        return 0;
    /* End of Sieve of Eratosthenes */The average execution times on the same machine on OEL-4.5 and OEL-5 are:
    MAX_PRIME_AREA     Mode         OEL-4.5         OEL-5     
                       real         0m9.196s        0m10.531s
       100000          user         0m9.189s        0m10.478s
                       sys          0m0.002s        0m0.010s
                       real         0m20.264s       0m21.532s
       200000          user         0m20.233s       0m21.490s
                       sys          0m0.020s        0m0.025s
                       real         0m30.722s       0m33.502s
       300000          user         0m30.684s       0m33.456s 
                       sys          0m0.024s        0m0.032s
                       real         1m10.163s       1m15.215s
       400000          user         1m10.087s       1m14.704s
                       sys          0m0.075s        0m0.079s
    ---------------------------------------------------------Does this ring a bell with anyone? Any clue why?
    N.J.

    An hour? Hard to believe or is your hardware that
    old?An hour? That's a super good time for 3 kernel
    packages (i686, xen and PAE) with all modules, plus 3
    kernel-devel packages, plus debuginfo package of
    150-580 MB where smart people at Red Hat decided to
    put uncompressed vmlinux image which is necessary for
    kernel profiling and debugging. Ah, I had a different kernel make process in mind.
    Oracle doesn't ship
    debuginfo package. Of course, this is when I build a
    "complete suite" of kernel rpm packages using
    unmodified spec file. And, to be honest, it takes
    much more than an hour, maybe even two hours. Another
    thing is compiling single i686 kernel without
    building a package. But it also takes at least half
    an hour. Anyway the time significantly depends on how
    many modules are selected to be built in.That what I was looking for.
    What's your time to build a single kernel (which
    version?) with default set of modules ? On which
    hardware ? I've only access to a root server right now, which is
    cat /proc/cpuinfo | grep "model name"
    model name      : AMD Athlon(tm) 64 Processor 3700+with about 2GB of RAM
    free -m
                 total       used       free     shared    buffers     cached
    Mem:          2024       1957         67          0        368       1291
    -/+ buffers/cache:        297       1727
    Swap:         3827         24       3803under
    uname -a
    Linux base 2.6.22-gentoo-r5 #5 PREEMPT Mon Sep 10 22:32:37 CEST 2007 i686 AMD Athlon(tm) 64 Processor 3700+ AuthenticAMD GNU/LinuxThis is what i did
    cd /usr/src/linux
    make clean
    time nice -n  19 genkernel --lvm2 --makeopts="-j2" --oldconfig all
    * Running with options: --lvm2 --makeopts=-j2 --oldconfig all
    * Linux Kernel 2.6.22-gentoo-r5 for x86...*
    mount: /boot mounted successfully!
    * config: >> Running oldconfig...
    * config: --no-clean is enabled; leaving the .config alone.
    *         >> Compiling 2.6.22-gentoo-r5 bzImage...
    *         >> Compiling 2.6.22-gentoo-r5 modules......
    real    17m30.582s
    user    16m8.480s
    sys     1m9.000sWhat could helped here was that I've switched off some modules and (maybe) the use of ccache.
    C.

  • Generating primes.  i know the problem, just can't fix it.

    I have to generate all the primes up to a given integer, but I'm failing horribly. I have to stay pretty close to what I've coded so far.
    Here's the class I constructed
    public class PrimeGenerator
         public PrimeGenerator()
         num=0;
         public PrimeGenerator(int num2)
         num=num2;
         public boolean isPrime()
         if (num==1)
              return false;
         if (num==2)
              return true;
         if ((num==3) || (num==5) || (num==7))
              return true;
         else if ((num%2==0) && (num%3==0) && (num%5==0) && (num%7==0))
              return false;
         return true;
         public int nextPrime()
         num++;
         while (!(isPrime()))
              num++;
         return num;
         private int num;
    }Here's the test program I wrote to test it
    import javax.swing.JOptionPane;
    public class PrimeGeneratorTest
         public static void main(String[] args)
         String input=JOptionPane.showInputDialog("Enter a number");
         int limit = Integer.parseInt(input);
         PrimeGenerator prime=new PrimeGenerator(limit);
         int p = prime.nextPrime();
         while (limit>p)
              System.out.print(p + " ");
              p =prime.nextPrime();     
         System.exit(0);
    }The only problem (I hope) is that the integer num of class PrimeGenerator is going to be set to that same as value as the object limit of the test, and the while loop in the test program is never executed. But everytime I change something in either program the result is just a different wrong answer. For example if I set num=0; in nextPrime(), then the while loop will execute in the program and it will be an endless loop displaying the number 2.
    Actually its probably easier to look at the program than listen to me...but I really need to figure out how to correct this because its eating away at my soul.

    Your main problem is, that your algorithm, that detects, wheter num is a prime number or not is wrong. Try to use another one (like the "Sieve of Eratosthenes"). Your PrimeGenerator class could then look something like this:
    import java.util.ArrayList;
    import java.util.Iterator;
    public class PrimeGenerator{
      private int num;
      private ArrayList a;
      public PrimeGenerator() {
        num=1;
        a=new ArrayList();
      public boolean isPrime()  {
        Iterator iter = a.iterator();
        int i;
        while(iter.hasNext()) {
          i = ((Integer)iter.next()).intValue();
          if(num%i == 0) {
            return false;
        a.add(new Integer(num));
        return true;
      public int nextPrime()  {
        num++;
        while (!(isPrime())) num++;
        return num;
    }Plus there is another problem with your test-class:
      PrimeGenerator prime=new PrimeGenerator(limit);Why do you set the num-field of the PrimeGenerator class to the limit you do not want to exceed in the testclass?

  • Procmail trouble migrating to Mavericks - everything delivered to /var/mail/ user

    My old hardware died Thanksigving afternoon, so I hastily migrated to the new machine I'd already been setting up with Mavericks. One post-migration problem was that user mail was delivered into /var/mail/<username> instead of into Maildirs. mail.log said it was delivering to procmail, but that's not where mail showed up. Removing (renaming) each user's .forward and .procmailrc files fixed this at the cost of turning off procmail's automatic filing.
    In the old setup, each user had a .forward file that said |/usr/bin/procmail, also a .procmailrc that started with
    # This causes delivery in maildir format.
    DEFAULT=$HOME/Maildir/
    In each user's home directory, Maildir was a symlink to /var/spool/imap/dovecot/mail/<some long hashcode>. Back in 10.6, each user owned their mail directory and all its contents.
    In Mavericks, the mail directories have moved to /Library/Server/Mail/Data/mail/<some long hashcode>. Those directories are completely owned by _dovecot. I repointed the symlinks, but wondered if the different ownership might be a problem.
    One seeming bug I found was that line 45 of /Library/Server/Mail/Config/dovecot/conf.d/10-mail.conf says
    mail_location = maildir:/Library/Server/Mail/Data/mail/%u
    Since %u is <username> and not <some long hashcode>, I think that should say
    mail_location = maildir:/Library/Server/Mail/Data/mail/users/%u
    But changing it and restarting dovecot had no effect. Only disabling procmail made mail go where it should.
    My bottom line question is, how can I get procmail working again?

    Possibly I've answered my own question-and-a-half. My mail is being sieved. For the record:
    Setting mail_debug=yes in /Library/Server/Mail/Config/dovecot/conf.d/10-logging.conf put some helpful notes into /Library/Logs/Mail/mail-debug.log. Searching for "sieve" in there revealed that dovecot was looking for per-user sieves as /Library/Server/Mail/Data/rules/<long-hash-code>/dovecot.sieve. That path was specified with %u in the dovecot config, so%u must really mean <long-hash-code>, not <username> as I thought. (That was the half-question.)
    So apart from having to create those directories and populate them, sieve was already configured and running as a dovecot plugin.

  • Trying to implement a quadratic sieve!

    Hi
    I am trying to write a quadratic sieve. Without posting the code, would anyone be willing to walk me through it, as to be completely honest, I am lost? The examples in the book 'Number Theory with Computer Applications' are as about as useful as a goldfish with a driving licence!
    Ron

    I suggest google:
    http://www.google.ca/search?hl=en&safe=off&q=quadratic+sieve+java&meta=
    or
    http://www.google.ca/search?hl=en&safe=off&q=quadratic+sieve&meta=

  • SA/Sieve Woes

    Hi all,
    We have MS 2005Q6 core patch -58 installed. Below is the story and problems that we have encountered when setting up Spam Assassin.
    SA is setup to label spam with addtag [SPAM] so that every spam email is tagged in the tcp_local channel. The spamfilter1_string_action looks like this:
    require ["addheader","fileinto"];
    addtag "[SPAM]";
    addheader "$U";
    fileinto "Spam";
    stop;Problem 1. In a user level sieve script, the (header :matches "Subject"
    "[SPAM]*") did match nothing even though the [SPAM] tag did appear in the
    final subject line. It looks as if the addtag processing is only done
    after the header match operations, or the header match uses the "original"
    subject line for the match. Is there anything wrong with the sieve script?
    After some time, we modified the script with the intention to give every scanned email detailed sa results even for non-spams, and at the same time add a new header for user leve sieve scripts.
    #mode=2,field= in spamassassin.opt
    require ["spamtest","relational","comparator-i;ascii-numeric","fileinto","addheader"];
    spamadjust "$U";
    addheader "Spam-Test: $U";
    if spamtest :value "ge" :comparator "i;ascii-numeric" "5"{
      addheader "Spam: Y";
      addtag "[SPAM]";
      fileinto "Spam";
    }else{
      keep;
    }Problem 2. The above script runs well, except one thing that cost me a full day debugging. Note the 2nd addheader line, which reads addheader "Spam: Y". The problem is, it seems that we cannot have a 2nd addheader in one single script, which is longer than 7 characters in length including the space in between. If you say addheader "ABCDE: Y", you are busted. The filter will just refuse to run. Is this a bug or something?
    OK, never mind, who care about a 7 byte header. We want to have a fine-grain control over the traditional email forwarding feature that uses mailForwardingAddress attribute. I suppose Sieve is more flexible when it comes to filtering and redirecting mail. So we disable the mailForwardingAddress, and use Sieve. So now, we try to setup a user level sieve to redirect important emails, even it is identified as spam like this:
    require ["fileinto","copy"];
    if header :match "Spam" "Y" {
      fileinto :copy "Spam";
    if header :match "Priority" "Urgent" {
      redirect "[email protected]";
    }Problem 3. When SA identifies a spam, it is marked as such with addtag [SPAM] (see code above). The tag should appear once. It is the case for the email left in the Spam folder of the server. But the email received by "[email protected]" contains 2 tags [SPAM] [SPAM] in the subject line. Clearly, SA is run twice, one for the incoming message, and one for the redirected message, and the log file confirms this. It seems that the redirect action cause the mail to be queued in the tcp_local channel, which causes SA to run. But it is interesting that the traditional emailForwardingAddress attribute kind of forwarding doesn't have this kind of behavior. Is there a way we can prevent SA from running twice in sieve to save resources and not to duplicate the tag?
    Anyone can shed some lights on these matters?
    Thanks in advance.
    PY

    Hi,
    SA is setup to label spam with addtag [SPAM] so
    that every spam email is tagged in the tcp_local
    channel. The spamfilter1_string_action looks like
    this:
    require ["addheader","fileinto"];
    addtag "[SPAM]";
    addheader "$U";
    fileinto "Spam";
    stop;Problem 1. In a user level sieve script, the (header
    :matches "Subject"
    [SPAM]*") did match nothing even though the [SPAM]
    tag did appear in the
    final subject line. It looks as if the addtag
    processing is only done
    after the header match operations, or the header
    match uses the "original"
    subject line for the match. Is there anything wrong
    with the sieve script?Please provide the actual spamfilter1_string_action you used - not just the 'cleaned' version.
    Also I should point out that matching on a modified subject header can lead to unexpected behaviour e.g. forwarded spam emails getting filtered to spam folder because [SPAM] appears in the subject line. It is much better to use the spamadjust/spamtest if possible.
    After some time, we modified the script with the
    intention to give every scanned email detailed sa
    results even for non-spams, and at the same time add
    a new header for user leve sieve scripts.
    #mode=2,field= in spamassassin.opt
    require
    ["spamtest","relational","comparator-i;ascii-numeric",
    "fileinto","addheader"];
    spamadjust "$U";
    addheader "Spam-Test: $U";
    if spamtest :value "ge" :comparator "i;ascii-numeric"
    "5"{
    addheader "Spam: Y";
    addtag "[SPAM]";
    fileinto "Spam";
    lse{
    keep;Problem 2. The above script runs well, except one
    thing that cost me a full day debugging. Note the
    2nd addheader line, which reads addheader "Spam:
    Y". The problem is, it seems that we cannot have a
    2nd addheader in one single script, which is longer
    than 7 characters in length including the space in
    between. If you say addheader "ABCDE: Y", you are
    busted. The filter will just refuse to run. Is this
    a bug or something?There is one limit you may be hitting (I found this one yesterday) and that is that spamfilterX_string_action is currently limited to a maximum of 256 characters - that is AFTER the expansion of the $U btw. Please log a support call (if you haven't already) and ask to be added to bug #6485247.
    There is a workaround to this limit and that is to use channel-level filtering, refer to my last reply in a forum question yesterday:
    http://forum.sun.com/jive/thread.jspa?threadID=109607
    OK, never mind, who care about a 7 byte header. We
    want to have a fine-grain control over the
    traditional email forwarding feature that uses
    mailForwardingAddress attribute. I suppose Sieve is
    more flexible when it comes to filtering and
    redirecting mail. So we disable the
    mailForwardingAddress, and use Sieve. So now, we try
    to setup a user level sieve to redirect important
    emails, even it is identified as spam like this:
    require ["fileinto","copy"];
    if header :match "Spam" "Y" {
    fileinto :copy "Spam";
    if header :match "Priority" "Urgent" {
    redirect "[email protected]";Problem 3. When SA identifies a spam, it is marked
    as such with addtag [SPAM] (see code above). The tag
    should appear once. It is the case for the email
    left in the Spam folder of the server. But the email
    received by "[email protected]" contains 2 tags
    [SPAM] [SPAM] in the subject line. Clearly, SA is
    run twice, one for the incoming message, and one for
    the redirected message, and the log file confirms
    this. It seems that the redirect action cause the
    mail to be queued in the tcp_local channel, which
    causes SA to run. But it is interesting that the
    traditional emailForwardingAddress attribute kind of
    forwarding doesn't have this kind of behavior. Is
    there a way we can prevent SA from running twice in
    sieve to save resources and not to duplicate the
    tag?
    Anyone can shed some lights on these matters?
    Thanks in advance.Well I'm not going to troubleshoot each of your issues as that will take me a ages - sieve scripts can be tricky. What is your overall goal of the filtering? From what you have mentioned so far it is:
    At the system level:
    -> add the [SPAM] tag to all spam emails
    -> add the X-Spam: Y to all spam emails emails (you should use X- for custom headers btw.)
    -> add the Spam-test: <score> to all scanned emails
    At the user level:
    -> filter all Spam emails to a spam folder
    -> forward non-spam high priority emails to another address
    Are you using separate front-end MTA/back-end store configuration and not using LMTP between the two? This will change whether spamadjust/spamtest can be used for the user level sieve rules.
    Regards,
    Shane.

  • Supported Sieve Extensions....

    I have not been able to find a definitive list of supported Sieve filter extensions. In particular, I am looking for an extension that will let me replace or rewrite a particular header in the message (specifically, the subject line of the message). The RFC lists just the basic actions, and the admin guide mentions a few related to Spamassasin functionality, but from reading the forums it seems that at least "addheader" is supported.
    Has anyone here had any experience using sieve filters to replace the subject line of a message? The "addtag" command will let me modify the subject line, but does not let me replace the subject in its entirety, which is what I need to do. I've found lots of proposed RFCs for sieve extensions, including "deleteheader" and "editheader" but the best answer I have found so far regarding messag server support for them is "we try to support what is in the RFC", which is somewhat vauge to me.
    Is there a command I can run that will list all the supported sieve commands?
    Thansk in advance for any help!
    BTW - I am running this version of MS:
    bash-3.00$ sudo /apps/msg_inst_dir/SUNWmsgsr/sbin/imsimta version
    Sun Java(tm) System Messaging Server 6.2-7.05 (built Sep 5 2006)
    libimta.so 6.2-7.05 (built 12:18:44, Sep 5 2006)
    SunOS uslcsec05 5.10 Generic_118833-02 sun4u sparc SUNW,Sun-Fire-280R

    Hi,
    Thanks for the info, I'll look into the milter stuff
    to see if that may give me a better fit in a future
    revision. The milter plugin should prove to be very powerful. Recent updates to the pre-release 6.3 code (which I really hope make it into the release version) now provides support for basically all of the milter email actions including:
    - Add headers (SMFIR_ADDHEADER)
    - Change body chunks (SMFIR_REPLBODY)
    - Add recipients (SMFIR_ADDRCPT)
    - Remove recipients (SMFIR_DELRCPT)
    - Change or delete headers (SMFIR_CHGHEADER)
    - Quarantine message (SMFIR_QUARANTINE)
    Writing a milter server (the MTA is the milter 'client') is pretty straight-forward if you have any C-code experience. There are any number of examples on the internet that you could work with.
    You right about the pipe channel, I realized after my
    last posting that combing sieve with a pipe channel
    would be a more lightweight way to go, and I am
    mostly done with my current implementation of that
    now. This is good approach. Sieve should be used to cut down on the messages to be processed as it is light-weight and fast, and then the pipe channel can handle the rest of the actual 'heavy lifting'.
    Are there any tips you might have regarding the
    scalability of sieve or the pipe channel? Do you
    know if every message that goes out to the pipe
    channel spawns a new process? Yes it does. Which is why you need to limit the messages that end up in the pipe channel to just those that you need to end up there.
    I vaugely recall there
    were some options for throttleing the number of
    messages processed in a given time frame, would that
    be the best way to make sure I don't kill my server
    if some clown in the HR department decides to blast
    out a few thousand messages at once? 8-)The pipe channel can queue up messages. You can limit the number of 'jobs' by using a job pool (defined in job_controller.cnf file and set in imta.cnf).
    thanks again for your help and advice, I really
    appreciate it.Good luck with your project. It is always interesting to hear how customers are using the product.
    Regards,
    Shane.

  • Testing sieve filter

    Hello,
    I would like to make some test with the sieve filter.
    The rule is stored in /tmp/filter :
    require ["fileinto", "reject", "vacation", "relational", "comparator-i;ascii-numeric", "regex", "envelope", "notify", "subaddress", "copy"];
    if header :contains "Subject" "{Spam?}"
    {fileinto "SPAM"; stop;}
    the command imsimta test -exp -mm -block -input=/tmp/filter gives :
    Expression: require ["fileinto", "reject", "vacation", "relational", "comparator-i;ascii-numeric", "regex", "envelope", "notify", "subaddress", "copy"];
    Expression: Expression: if header :contains "Subject" "{Spam?}"
    Expression: Expression: {fileinto "SPAM"; stop;}
    Expression: Dump: header:2000115;0 3 1 :contains 1 "Subject" 1 "{Spam?}"
    Dump: if 8 ; fileinto:2000113;0 1 1 "SPAM" ; "" stop
    Evaluation error: No message context for header test
    But when I add -message=/tmp/17.msg where /tmp/17.msg is :
    Received: from mmp-1-1.sipr-dc.ucl.ac.be ([127.0.0.1])
    by mmp.sipr-dc.ucl.ac.be (Sun Java System Messaging Server 6.2-3.04 (built Jul
    15 2005)) with SMTP id <[email protected]> for
    [email protected]; Mon, 02 Oct 2006 11:04:43 +0200 (CEST)
    Date: Mon, 02 Oct 2006 11:04:38 +0200 (CEST)
    Date-warning: Date header was inserted by mmp.sipr-dc.ucl.ac.be
    From: [email protected]
    Subject: {Spam?} test number 3
    To: [email protected]
    Message-id: <[email protected]>
    test number 3
    the command imsimta test -exp -mm -block -input=/tmp/filter -message=/tmp/17.msg gives
    15:49:33.27: Exit code = 13 (13) - IMTA__ERROPENINP, error opening file !AD for input: Permission denied
    What's wrong ?
    # imsimta version
    Sun Java(tm) System Messaging Server 6.2-3.04 (built Jul 15 2005)
    libimta.so 6.2-3.04 (built 01:32:55, Jul 15 2005)
    SunOS mmp-1-1 5.10 Generic_118855-14 i86pc i386 i86pc

    Sounds like Messaging is complaining that the file itself has wrong ownership/permissions to be read. It's either your filter file, or the message file.

  • Generate prov.xml for Creative Cloud. Return Code 27

    We're trying to follow this guide (Creative Cloud Help | Using Adobe Provisioning Toolkit Enterprise Edition) to serialize a package (or something). We're stuck on generating prov.xml. My best attempt at an entry is:
    C:\Program Files (x86)\Common Files\Adobe\OOBE\PDApp\CCP\utilities\APTEE>adobe_prtk.exe --tool=VolumeSerialize --generate --serial=xxxx-xxxx-xxxx-xxxx-xxxx-xxxx --regsuppress=ss --eulasuppress --locales=en_US --provfilepath=C:\Program Fil
    es (x86)\Common Files\Adobe\OOBE\PDApp\CCP
    It says half of this is optional, but I'm skeptical.
    Anyway, I'm getting return code 27. This indicates that it is unable to edit the prov.xml file specified. I didn't specify a prov.xml file, I'm trying to make one. The syntax I'm using differs from what I found on the page I linked, as that was giving me syntax errors. I lifted this off someone else's code. I've tried just about every variation I can think of. Any help would be appreciated.
    This is on Windows

    One of these links may help
    http://helpx.adobe.com/creative-cloud/packager.html
    http://forums.adobe.com/community/download_install_setup/creative_suite_enterprise_deploym ent

Maybe you are looking for

  • Newby question: I keep on getting "No size set" error

    Hello, I'm trying to integrate an Oracle database into my ASP.NET application and I keep on getting an error: "Parameter: ENTITY_NAME. No size set for variable length data type: String" The parameter is set as VarChar2 in the database, size 50, and t

  • Icloud v 4.0 does not install on windows 7 64 bit

    I tried everything. I de-installed the previous version, I really don't know what is wrong. I install it and the last section of the installation fails. Then it de-installs and tells me to contact the person who controls the installation!

  • Dell Precision T5810 Core options and GPU config? Running CC on virtual desktops?

    Hi, two questions really but didn't want to start multiple threads. I tried searching for answers to my questions but was not very successful so am trying to post. I am looking at buying some computers for our office which will be using the CC subscr

  • Internal table export and import in ECC 5.0 version

    Hi friends, I am trying to export and import internal table from one program to other program. The below… export and import commands are not working when I run the program in background (using SUBMIT zxxxx via JOB name NUMBER number…..) EXPORT ITAB T

  • Flash CS5 Basic Help!

    I am very new to this program and am struggling to get past this one simple little thing! I clicked New > Action Script 3.0 and am trying to do some of the basic tutorials and cant even get past the first one! I am trying to draw a filled in rectangl