Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 10 of 10

Thread: Printing Sum of Primes of a number

  1. #1
    Junior Member
    Join Date
    Jun 2010
    Posts
    6
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Printing Sum of Primes of a number

    I'm trying to print the sum of the prime numbers of a given number from the console. I think my test in my while loop might be wrong, but I'm not 100% sure. Any help, I would appreciate. Thanks in advance.

    import java.util.*;
     
    public class PrimeSum
    {
        public static int isPrime(int num)
        {
            int sum = 0;
            int factor = 1;
            while(factor <= num)
            {
                if(num % factor != 0)
                {
                    sum += factor;
                    factor ++;
                }
                else
                {
                    factor ++;
                }
            }
            return sum;
        }
     
        public static void main(String[] args)
        {
            System.out.println("The program gets the sum of all prime numbers.");
     
            Scanner scan = new Scanner(System.in);
     
            System.out.print("Enter a number: ");
            int num = scan.nextInt();
     
            int sum = isPrime(num);
     
            System.out.println(sum);
        }
    }


  2. #2
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Printing Sum of Primes of a number

    Did you mean the sum of all prime factors of a number, or the sum of all prime numbers less than (and/or equal) to the number? The two will provide very different results.

  3. #3
    Junior Member
    Join Date
    Jun 2010
    Posts
    6
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Printing Sum of Primes of a number

    The later...

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,163
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Printing Sum of Primes of a number

    Try debugging your code by printing out the results of the tests so you can see what is happening. Add some println()s to the loop in the isPrime() method.

  5. #5
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Printing Sum of Primes of a number

    Ok, I'm not that interested in coding this out, so I'll run you through what is going on with your code.

    Lets call isPrime(5). This should return 3 (unless you consider 1 a prime number, which would result in 4).
    Now what that does return is 9. Wrong answer . So, what is happening?

    We start the method.
    Sum = 0. Factor = 1. num = 5.
    Start the loop. 1 <= 5? Yes. num%factor != 0? No, that equals 0. Increase factor.
    2 <= 5? Yes. num%factor != 0? Yes, that equals 1. sum = 0+2. Increase factor.
    3 <= 5? Yes. num%factor != 0? Yes, that equals 2. sum = 2+3. Increase factor.
    4 <= 5? Yes. num%factor != 0? Yes, that equals 1. sum = 5+4. Increase factor.
    5 <= 5? Yes. num%factor != 0? No, that equals 0. Increase factor.
    6 <= 5? No. Return 9.

    So, if you arent aware of what mod ( % ) does, it returns the remainder from division. Which means. When we do 5%1, we are actually doing 5/1 and returning the extra. So, 5/1 = 5 with a remainder of 0. 5/2 = 2 with a remainder of 1. 5/3 = 1 with a remainder of 2. 5/4 = 1 with a remainder of 1. 5/5 = 1 with a remainder of 0. Mod is getting its answer from the remainder of the integer division. Hopefully that can help you.

  6. #6
    Junior Member
    Join Date
    Jun 2010
    Posts
    6
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Printing Sum of Primes of a number

    So that shouldn't even be part of the test. I'm confused then about what I need to do, I have been scratching my head all day it seems... I thank you for the help.

  7. #7
    Junior Member
    Join Date
    Jun 2010
    Posts
    6
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Printing Sum of Primes of a number

    I tried going back to the basic of is a number prime and working it that way, and I sort of see the problem... How do I kept the sum going even though that loop is changing it?

    import java.util.*;
     
    public class PrimeSum3
    {
        public static void main(String[] args)
        {
            Scanner scan = new Scanner(System.in);
            System.out.println("Enter a number: ");
            int input = scan.nextInt();
            boolean prime = true;
     
            int num = 0;
            int start = 2;
            while(start < input)
            {
                if(input % start == 0)
                {
                    prime = false;
                }
                if(prime == true)
                {
                    num = start;
                    System.out.print(num + " " + start);  //for test purposes
                    num += num;
                }
                System.out.print(" " + num + " .");  //for test purposes
                start++;
            }
     
            if(prime == false)
            {
                System.out.println(input + " is not prime");
            }
            else if(prime == true)
            {
                        System.out.println(input + " is prime");
            }
            System.out.println(num);
        }
    }

    //Output
    2 2 4 .3 3 6 .4 4 8 .5 is prime
    8

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,163
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Printing Sum of Primes of a number

    Your debug output should be a bit more verbose. It's hard to tell what the list of numbers you've posted means:
    println("num=" + num + ", start=" + start);

    I have no idea what this means:
    System.out.print(" " + num + " .");

  9. #9
    Junior Member
    Join Date
    Jul 2010
    Posts
    5
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default Re: Printing Sum of Primes of a number

    You need to go step-by-step. First find whether a number is prime (so, write a method which tells whether a given number is prime) and then add it to the sum (write a method which adds only prime numbers).

    The following works for you:

    public class SumOfPrimes{

    public boolean isPrime(int x){
    for(int i=2;i<x;i++){
    if(x%i == 0)
    return false;
    }
    return true;
    }

    public int sumOfAllPrimes(int x){
    int sum = 0;
    for(int i=2;i<x;i++){
    if(isPrime(i)){
    sum = sum+i;
    System.out.println("sum: "+sum);
    }
    }
    return sum;
    }

    public static void main(String[] args){
    int number = 6;
    SumOfPrimes sop = new SumOfPrimes();
    System.out.println("sum of all primes less than the given number is: "+sop.sumOfAllPrimes(number));
    }
    }

  10. The Following User Says Thank You to kamalivy For This Useful Post:

    CodeNewb (July 12th, 2010)

  11. #10
    Junior Member
    Join Date
    Jun 2010
    Posts
    6
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Printing Sum of Primes of a number

    I doubt I would of ever figured it out... Thanks for you help.

    I like this by the way, I'm just learning java and I think this is neat...
    SumOfPrimes sop = new SumOfPrimes();
    System.out.println("sum of all primes less than the given number is: "+sop.sumOfAllPrimes(number));

Similar Threads

  1. [SOLVED] Printing Array without printing empty elements
    By CarlMartin10 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: April 12th, 2010, 02:41 AM
  2. letter to number
    By silverspoon34 in forum Java Theory & Questions
    Replies: 1
    Last Post: November 27th, 2009, 07:01 AM
  3. Reverse Number
    By java1 in forum Java Theory & Questions
    Replies: 2
    Last Post: October 28th, 2009, 10:19 AM
  4. Calculate primes help
    By TommyFiz in forum What's Wrong With My Code?
    Replies: 3
    Last Post: October 27th, 2009, 11:41 PM
  5. [SOLVED] How to string a decimal number in Java?
    By Lizard in forum Loops & Control Statements
    Replies: 6
    Last Post: May 14th, 2009, 03:59 PM