sum of prime numbers in java code example
Example 1: java prime numbers
public class Main {
public static void main(String[] args) {
for (int i = 2; i < 1_000_000; ++i) {
boolean isPrime = true;
int sqrt = (int)Math.ceil(Math.sqrt(i));
for (int divisor = 2; divisor <= sqrt; ++divisor) {
if (i % divisor == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println(i);
}
}
}
}
Example 2: sum of prime numbers in a digit in java
import java.util.*;
public class PrimeDigit
{
public boolean IsPrime(int i)
{
boolean b=true;
int d=2;
while(d<i/2)
{
if (i%d==0)
{
b=false;
break;
}
d++;
}
return b;
}
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter A Number : ");
int i=sc.nextInt();
int s=0,r;
PrimeDigit pd=new PrimeDigit();
while(i>0)
{
r=i%10;
if(pd.IsPrime(r))
{
s = s + r;
}
i = i / 10;
}
System.out.print("Sum Of The Prime Digits : " + s );
}
}
Example 3: sum of numbers in java
public class SumNatural {
public static void main(String[] args) {
int num = 100, sum = 0;
for(int i = 1; i <= num; ++i)
{
sum += i;
}
System.out.println("Sum = " + sum);
}
}