sum of all prime numbers between 100 and 200 - java

I'm actually about to loose my mind... The code I wrote displays every kind of "sum" and "count" between the actual last result I want to display with System.out.print(...). Can someone help me please? What did I do wrong for it to display everything?
public class Prim {
public static void main(String[] args) {
int end = 11;
int count = 1;
long sum = 0;
for (int number = 10; count<=end; number++) {
if (isPrim(number)) {
sum = sum + number;
count++;
System.out.println(sum);
}
}
}
public static boolean isPrim(int number){
for (int i=2; i<number; i++) {
if (number % i == 0) {
}
}
return true;
}
}

A few things.
First, your isPrim can be optimised so that i only increments until sqrt(number).
Second, you need to return false if (number%i == 0) is true. Right now, it's always returning true, which is why your code is outputting all sums.
Third, you need to change istPrimeZahl to isPrim (or vice versa), as you haven't defined istPrimeZahl anywhere.
Fourth, you can change sum = sum + number to simply sum += number.
Finally, you probably want to move your System.out.print line two lines below, so that it only prints the sum after the loop has ended, not at every iteration of the loop.
(Also, you might want to change your for loop so that it starts at 100, not 10 :) )
If you want the final version, I've pasted it here:
public class Prim {
public static void main(String[] args) {
int end = 200;
int count = 0;
long sum = 0;
for (int number = 100; number<=end; number++) {
if (isPrim(number)) {
sum += number;
count++;
System.out.println(sum);
}
}
}
public static boolean isPrim(int number){
for (int i=2; i*i<=number; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}

The isPrim function is missing a 'return false' after the if statement. This means that isPrim will always return true, and consequently every number will get written to the console.
The System.out.print is also within for-loop, so it will print an updated sum each time. It's unclear if this is intentional, but if you want to only get a single result then that should also be moved two lines lower.

For sum of prime numbers between 100 to 200, try this code:
public class Primzahlen {
public static void main(String[] args) {
int sum = 0;
for (int i = 100; i < 200; i++)
if (isPrim(i))
sum += i;
System.out.print(sum);
}
public static boolean isPrim(int num) {
for (int i = 2; i <= Math.sqrt(num); i++)
if (num % i == 0)
return false;
return true;
}
}

Related

Extracting Prime Numbers

I need to create a method that will mark the prime numbers and return the count of the prime numbers.
I went this far:
private static int[] extractPrimesNumbers(int[] array, int countOfPrimeNumbers) {
int[] primeNumber = new int[countOfPrimeNumbers];
int position = 0;
for (int j = 2; j < array.length; j++) {
for(int key : array) {
if(j == 2) {
array[position] = j;
}
boolean isDividedByJ = j % j == 0;
boolean isDividedbyTwo = j % 2 != 0;
if(isDividedByJ && isDividedbyTwo) {
array[position] = j;
position++;
j++;
}
}
I don't know how to mark none prime numbers. I was thinking the good way is marking the none prime with 0, then calculate the amount of value from position/index which are higher than 0.
Worth to mention this all things needs to be in one method using array. Can't use any standard solution for Prime using external boolean methods.
just return an array of the numbers that are prime, no need to mark. and the diff in the cont of the new array and the old one gives you a cont of the non prime as well.
Here is my solution approach.
1) First crete a very simple method to check whether a number is prime or not. See below:
public static boolean checkPrime(int number) {
if (number <= 1) {
return false;
}
System.out.println(number);
for (int i=2; i <= Math.sqrt(number); i++) {
if(number % i == 0) {
System.out.println(i);
return false;
}
}
return true;
}
2) Create another method that will loop through your array and call the above method:
public static int numOfPrimesInArray(int[] arr){
int counter = 0;
for (int num: arr){
if (checkPrime(num)) counter++;
}
return counter;
}
3) Then simply call this from your main method:
public static void main(String[] args){
int[] nums = {1,2,3,5,6,7,8,9,10};
int primes = numOfPrimesInArray(nums);
System.out.println(primes);
}
If I did not make any mistake when writing this shoul give you the number of primes in your array.
I solved the problem with Python. I tried a couple of alternatives and this one is the quickest. Still, I encountered a memory overflow at 1000000.
n = int(input("Type a number"))
primes = 0
for j in range(2,n+1):
for k in range(2,j):
if j%k==0:
primes = primes +1
#print(j)
break
print(n-1-primes)

Returning and Summing the Odd Numbers of an Array

I'm trying to add all the odd numbers in an array and return it. Any thoughts on what I'm doing wrong?
Example:
Input:
Array- [12,6,7,15,1]
It would return 23
public static int sumOdds(int[] numbers) {
sum = 0;
for(int i = 0; i < numbers.length; i++) {
if (numbers%2==0)
return 0;
else (numbers[i] % 2 != 0) {
sum += numbers;
return sumOdds;
}
}
public static int sumOdds(int[] numbers) {
int sum = 0;
for(int i = 0; i < numbers.length; i++) {
if(numbers[i] % 2 != 0) {
sum += numbers[i];
}
}
return sum;
}
This should work. return statements should not be within your if and else statements, as they will end the execution of the program immediately.
And a Java 8+ solution would be
public static int sumOdds(int[] numbers) {
return Arrays.stream(numbers).filter(n -> n % 2 == 1).sum();
}
There are a few issues here. First of all, the mod operation is not going to work on an array. It needs to be performed on a single number. Furthermore, you are immediately returning the sumOdds without allowing the entire loop to complete.
This would work.
public static int sumOdds(final int[] numbers) {
int sumOdds = 0;
for (int number : numbers) {
if (number % 2 != 0) {
sumOdds += number;
}
}
return sumOdds;
}
Or better yet, use streams.
int sumOdds = IntStream.of(12, 6, 7, 15, 1).filter(number -> number % 2 != 0).sum()

Printing Perfect Numbers between 1-100 using Java

I don't know what is the problem with my code. It should print all the perfect numbers between 1-100. I tried with nested for-loop, do while loop and for-loop. However, the code seems to be incorrect.
class CompProject1
{
public static void main()
{
int num, sum=0;
int i;
for(num=1; num<100; num++)
{
for(int j = 1; j<=num ; j++)
{
if(num%j==0)
{
sum = sum+j;
}
}
if(sum==num)
{
System.out.println(sum);
}
}
}
}
Change your code to :
public static void main(String[] s1) throws Exception {
int num, sum = 0;
int i;
for (num = 1; num < 100; num++) {
for (int j = 1; j <= num - 1; j++) { // change made here
if (num % j == 0) {
sum = sum + j;
}
}
if (sum == num) {
System.out.println(sum);
}
sum = 0; // change made here
}
}
Key takeaways:
Reset sum to 0 once done with inner iteration
In your inner for-loop you need to check if till num - 1 and not num because every number is divisible by itself
1) you definitely need to reset your sum variable for every iteration, so you should do int sum = 0; in every loop.
2) you need to iterate while j <= num/2;!
3) consider using Java 8, I'll write some sample here for you.
See my example here, this is so beautiful:
public class PerfectNumbersDemo {
public static void main(String[] args) {
IntStream.range(1, 100)
.filter(PerfectNumbersDemo::isPerfect)
.forEach(System.out::println);
}
private static boolean isPerfect(int number) {
return number == IntStream.rangeClosed(1, number / 2)
.filter(i -> number % i == 0)
.sum();
}
}
This seems to be an assignment or homework question. You are meant to solve this by yourself and not ask it to the people on Stack overflow.
However, what you are looking for has an answer here. Beware! This code prints if the input number is perfect number or not but does not print all the numbers below 100 that could be perfect numbers. That is your homework.
You need to:
sum = 0 with every loop iteration
iterate until < num and not <= num
Here's the fixed code:
public static void main(String[] args) {
int sum;
for(int num = 1; num < 100; num++) {
sum = 0;
for(int j = 1; j< num; j++) {
if(num % j == 0) {
sum += j;
}
}
if(sum == num) {
System.out.println(sum);
}
}
}
Output:
6
28
So, your code have some minor problems and I will try to pinpoint them out.
1.First of all your sum variable should be inside the first for loop
2. The limit upto which the second loop will run will be j<num not j<=num because, for the perfect number, the number itself shouldn't be counted in the sum.
You code will look like this.
I don't know what is the problem with my code. It should print all the perfect numbers between 1-100. I tried with nested for-loop, do while loop and for-loop. However, the code seems to be incorrect.
class CompProject1 {
public static void main()
{
int num;
for(num=1; num<100; num++)
{
int sum = 0;
for(int j = 1; j<=num ; j++)
{
if(num%j==0)
{
sum = sum+j;
}
}
if(sum==num)
{
System.out.println(sum);
}
}
}
}
public class factors{
public static void main(String args[]){
int sum=0;
for(int k=2;k<=30;k++){
for(int i=1;i<k;i++)
{
if(k%i==0)
sum=sum+i;
}
if(k==sum)
System.out.println(sum);
sum=0; //sum=0 is very important.
}
}
}
OUTPUT
6
28
class PERFECT
{
public static void main(String args[])
{
int i,j,S,
for(i=1;i<=100;i++)
{
S=0
for(j=1;j<i;j++)
{
if(i%j==0)
S+=j;
if (S==i)
System.out.println(i+"is perfect");
}
}
}
}
Here is an alternate way of finding perfect numbers.
if 2p-1 is prime when p is prime. Then (2p-1)(2p-1) is a perfect number. 2p-1 is known as a Mersenne Prime
As these numbers get real big real fast, using BigInteger is recommended.
This computes the first 10 perfect numbers.
int N = 10;
int count = 1;
for(int i = 2; i < 10_000; i += i == 2 ? 1 : 2) {
BigInteger val = BigInteger.valueOf(i);
if (val.isProbablePrime(99)) {
BigInteger mersenne1 = (BigInteger.ONE.shiftLeft(i)).subtract(BigInteger.ONE);
if (!mersenne1.isProbablePrime(99)) {
continue;
}
BigInteger mersenne2 = BigInteger.ONE.shiftLeft(i-1);
System.out.printf("%3d: %,d\n",count, mersenne1.multiply(mersenne2));
if (count++ >= N) {
break;
}
}
}
prints
1: 6
2: 28
3: 496
4: 8,128
5: 33,550,336
6: 8,589,869,056
7: 137,438,691,328
8: 2,305,843,008,139,952,128
9: 2,658,455,991,569,831,744,654,692,615,953,842,176
10: 191,561,942,608,236,107,294,793,378,084,303,638,130,997,321,548,169,216

Calculating the 10001 prime number, no output is printed

public class Prime
{
public static void main(String [] args)
{
int num = 3;
int counter = 1;
boolean flag = true;
while(counter < 10001)
{
for(int i = 2; i < num; i++)
{
if(num%i==0)
{
flag = false;
}
}
if(flag)
{
counter++;
}
num++;
}
System.out.println(num);
}
}
Whenever I run this code, no result is printed out. I'm assuming its because the code is inefficient, but I don't know what is wrong with this code.
Your problem is that you don't reset flag to true before the for loop; so once it is false, it remains false, so counter is never incremented, meaning the while loop guard never becomes false.
This is an example of why you should declare variables in the tightest possible scope (i.e. inside the while loop).
while(counter < 10001)
{
int flag = true;
for (...) {...}
if (flag) { counter++; }
// ...
}
It's also an example of why you should make sure your code is correct before you think about whether it is efficient. Had you debugged the code (or even just added in a few System.out.printlns), you could have found that it wasn't actually doing the right thing.
As mentioned by #AndyTurner you should declare flag = true; in while loop and also there is a slight error in your logic for finding the prime number.
You are incrementing the num after it is checked for prime. So, if your 3rd prime is 5, then it will print 6 as the answer. lly, if your 10001th prime is X, then it will print X + 1 as the answer.
I have posted the correct logic for your problem below. I hope it helps you.
public class Main
{
public static void main(String [] args)
{
int num = 2;
int counter = 1;
boolean flag = true;
while(counter < 10001)
{
flag = true;
num++;
for(int i = 2; i < num; i++)
{
if(num%i==0)
{
flag = false;
}
}
if(flag)
{
counter++;
}
}
System.out.println(num);
}
}
Its not printing cause its going in infinite loop as counter is not incremented once flag become false
public static void main(String [] args)
{
int num = 3;
int counter = 1;
boolean flag = true;
while(counter < 10001)
{
flag = true;
for(int i = 2; i < num; i++)
{
if(num%i==0)
{
flag = false;
}
}
if(flag)
{
counter++;
}
num++;
}
System.out.println(num);
}
Try this. hope it helped

While loop numbers sum

I need help on how to calculate sum of the numbers that while loop prints. I have to get numbers 1 to 100 using while loop and calculate all those together. Like 1+2+3...+98+99+100. I can get numbers but can't calculate them together. Here's my code:
public class Loops {
public static void main(String[] args) throws Exception {
int i = 1;
while (i < 101) {
System.out.print(i);
i = i + 1;
}
}
}
How do I make it only print the last sum? If I try to trick the equation it just hangs.
Use another variable instead of i which is the loop variable:
int i = 1;
int sum = 0;
while (i < 101) {
sum += i;
i++;
}
Now sum will contain the desired output. In the previous version, you didn't really loop on all values of i from 1 to 101.
First either change your sum variable or index variable
public class Loops {
public static void main(String[] args) {
int sum = 0;
int i = 1;
while (i < 101) {
sum = sum + i;
++i;
}
System.out.println(sum);
}
Your sum (i) is also your index. So each time you add to it, you're skipping numbers which you want to add to it.
public class Loops {
public static void main(String[] args) {
int sum = 0;
int i = 1;
while (i < 101) {
//System.out.print(i);
sum = sum + i;
++i;
}
System.out.println(sum);
}
Alternatively, use the Gauss sum: n(n+1)/2
So, the end sum is 100(101)/2 = 5050
Try the following. Moved the values around a bit to ensure that you add up to 100 and always show the sum.
public static void main(String[] args) throws Exception {
int i = 1;
long tot = 1;
while (i < 100) {
i += 1;
tot += i;
System.out.print("Number :" + i + " ,sum="+tot);
}
}
public class Loops {
public static void main(String[] args) throws Exception {
int i = 1;
int sum = 0;
while (i < 101) {
sum = i + 1;
}
System.out.print(sum);
}
}

Categories