Reputation: 125
What is wrong in my code?
Expected output=1060
I checked with 1000 prime numbers sum. It will show correctly output 3682913
public class PrimeNumber {
public static void main(String args[]){
int number = 2;
int count = 0;
long sum = 0;
while(count <100){
if(isPrimeNumber(number)){
sum += number;
count++;
}
number++;
}
System.out.println(sum);
}
private static boolean isPrimeNumber(int number){
for(int i=2; i<=number/2; i++){
if(number % i == 0){
return false;
}
}
return true;
}
}
Upvotes: 4
Views: 7278
Reputation: 41
import java.util.Scanner;
public class Trial{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean flag = false;
int max = 1000001;
long[] a = new long[max];
a[0] = 2;
int i = 3,j=0;
long sum = 2;
int t = in.nextInt();
for(int a0 = 0; a0 < t; a0++){
long sum1 = 0;
int n = in.nextInt();
if(n>=i){
while(i<=n){
for(int y=0;a[y]<=Math.sqrt(i);y++){
if(a[y]==0){
break;
}
else if (i%a[y]==0){
flag = true;
break;
}
}
if(!flag){
a[++j]=i;
sum+=i;
}
flag =false;
i+=2;
}
System.out.println(sum);
}
else{
for(int y=0;a[y]<=n&&a[y]!=0;y++){
sum1+=a[y];
}
System.out.println(sum1);
}
}
}
}
here i stored prime numbers in an array if there is any query for the numbers which are already present in the array first 'if' statement will handle it and simple the sum upto that no. will be printed.This will save a lot time to recalculate the prime numbers and find their sum.
Upvotes: 0
Reputation: 6473
Currently, you are counting the first 100 primes, not the primes found in the range 1 - 100. You can lose the count variable entirely here.
Your code can be simplifed as such, using a for loop instead to go from 2 to 100 (1 not included, of course)...
public class PrimeNumber {
public static void main(String args[]) {
long sum = 0;
for (int number = 2; number <= 100; number++) {
if (isPrimeNumber(number)) {
sum += number;
}
}
System.out.println(sum);
}
private static boolean isPrimeNumber(int number){
for (int i = 2; i <= number / 2; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
Upvotes: 1
Reputation: 926
You can use the below given code to find the sum of first prime numbers between 1 to 100. It will give you correct output.
public class PrimeNumber {
public static void main(String args[]){
int number = 2;
int sum = 0;
while(number <= 100){
if(isPrimeNumber(number)){
sum += number;
}
number++;
}
System.out.println(sum);
}
private static boolean isPrimeNumber(int number){
int sqrt = (int) Math.floor(Math.sqrt(number));
for(int i = 2; i <= sqrt; i++){
if(number % i == 0){
return false;
}
}
return true;
}
}
Upvotes: 1
Reputation: 18933
You are counting up to 100 primes but not up to 100 numbers.
So your while loop should run up to 100 numbers.
This should be your main method:
int number = 2;
int count = 0;
long sum = 0;
while(number <= 100){
if(isPrimeNumber(number)){
sum += number;
count++;
}
number++;
}
System.out.println(sum);
}
This would give your output 1060.
Upvotes: 5