The objective is to add all the prime numbers before an arbitrary input. I am wondering what exactly this person has done through this code. I am not this advanced, and I do not how to work with particularly the int[] a variable. What is the int[] a command called? Could you please teach me how to write it without the int[] a variable? My life would be indebted to whomever helps me out.

int n;
int i, j, sum;
int[] a;

Scanner sc = new Scanner(System.in);
n = sc.nextInt();

sum = 0;
a = new int[n];
for (i = 2; i < n; ++i)
    a[i] = i;

for (i = 2; i < n; ++i) {
     if (a[i] != 0) {
         sum += a[i];

         for (j = 2 * i; j < n; j += i)
             a[j] = 0;
     }
}

System.out.println("The sum of all primes up to " + n + " is " + sum);

Recommended Answers

All 4 Replies

ola,

int[] a; would be an array, and the length of this array would be equel to the user input(which would be n) a sequence of integers, like a list if you will

i.e
it will hold 1,2,3,4,5,6...and in my example if you would like to access the 3 element in the array you would do it like this
int b = a[2];
and b will now equel 3.

an array starts with 0: i.e a[0] would equel 1.


more than that i cant help as it is pretty straight forward. Google "Array java"

krefie

int n;
int i, j, sum;
int[] a;

Scanner sc = new Scanner(System.in);  // create a scanner object for reading in
n = sc.nextInt();                     // accept only integer from user input

sum = 0;   // initialize sum of value
a = new int[n];  // create integer Array size of 'n' as user input
for (i = 2; i < n; ++i)  // loop starts from index 2 to n (not include n)
  a[i] = i;              // assign the value of index to each of its own array

for (i = 2; i < n; ++i) {  // again, start loop from 2 until n (not include n)
  if (a[i] != 0) {  // test if at a[i] is not equal to 0
    sum += a[i];    // add it to sum

    // now, each of any sub up to n that is the multiplication of 'i' should not be
    // a prime number (obviously, it can be divided by 'i'), 0 them all out
    for (j = 2 * i; j < n; j += i) {
      a[j] = 0;
  }
}

System.out.println("The sum of all primes up to " + n + " is " + sum);

One note about this code is that the 'sum' will not include the value of 'n'. For example, a user enter 11. The program will add 2 + 3 + 5 + 7 = 17.

use this code:
what u have asked is a very simpler task. Use this logic
Let n be the arbitary no upto what u want sum of primes
for(i=2;i<=n;i++)
{
if(n/i==0)
{
s+=i;/here s is the sum and initially it should be declared as s=0
}
}
System.out.println("the sum of all primes up to "+ n+"is"+sum);

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.