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)
Related
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()
So, I wanted to write a method that would create an array containing all divisors of a certain number. So I created an empty array (int[] divisors) that would later get it's numbers through a for-loop but it says that the array hasn't been initialized yet. What should I do?
The output of the method would later be used to find the greatest common divisor of two numbers, so it's important that the numbers in the array are ordered from smallest to biggest. I know there's a much easier solution to do this, but I want do it using arrays, because I want to focus on learning those at the moment.
public static int[] allDivisors(int number) {
int[] divisors;
int counter= 0;
for (int i = 0; i <= number; i++) {
if(number % i == 0) {
divisors[counter]= i;
counter++;
}
}
return divisors;
}
I couldn't find any proper solutions to my problem online so I hope someone we'll be able to help me out here. All I need is a way to add specific elements to an array which I can't define beforehand (in that case, all divisors of a certain number.) Thanks in advance for all your answers!
Array is not the proper data structure for this case because you need to initialize it with a size (integer number) prior of its use.
But you don't know how many items you will store in the array, right?
So you must use an ArrayList like this:
public static ArrayList<Integer> allDivisors(int number) {
ArrayList<Integer> divisors = new ArrayList<>();
for (int i = 1; i <= number; i++) {
if(number % i == 0) {
divisors.add(i);
}
}
return divisors;
}
I also changed in the loop:
int i = 0
to
int i = 1
to avoid division by 0 later in:
number % i
Also you don't need counter.
You can call this method in your code:
int number = 30;
ArrayList<Integer> list = allDivisors(number);
System.out.println("The divisors of " + number + " are:");
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + " ");
}
and it will print:
The divisors of 30 are:
1 2 3 5 6 10 15 30
If you strictly want to do this using arrays, try below changes to your program.
public static int[] allDivisors(int number) {
int[] divisors = new int[number]; // Have to initialize the array
int counter= 0;
for (int i = 1; i <= number; i++) { // i should start from 1; not from zero. Otherwise you get ArithmeticException (divide by zero)
if(number % i == 0) {
divisors[counter]= i;
counter++;
}
}
int[] trimmedDivisors = new int[counter];
System.arraycopy(divisors, 0, trimmedDivisors, 0, counter);
return trimmedDivisors;
}
In java before you use array you must be initializate it.
public static int[] allDivisors(int number) {
int[] divisors = new int[number];
int counter= 0;
for (int i = 0; i <= number; i++) {
if(number % i == 0) {
divisors[counter]= i;
counter++;
}
}
Arrays.sort(divisors);
return divisors;
}
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;
}
}
I'm having trouble in getting the rest of the numbers after I sum up the first 3 elements. This is the question that it asks me: "Write a method that takes an array. return true if the sum of the first three elements in the array is less than the sum of the rest of the elements of the array."
Therefore 5 5 5 5 2 2 should be false. Since the first 3 numbers sum are greater than the sum of 5 2 2. My program returns true for this question and I would appreciate any help.
public static boolean sumThree(int [] myArray)
{
int sum = 0;
for(int i = 0; i < myArray.length; i++)
{
sum += myArray[i];
}
int sumof3E = myArray[0] + myArray[1] + myArray[2];
if(sum > sumof3E)
{
return true;
}
else if(sumof3E < sum)
{
return false;
}
else
{
return false;
}
}
You shouldn't include the first three elements of the array. Those have to be exclusive of the summation.
Change the for loop control variable to this:
for (int i = 3; i < myArray.length; i++) {
sum += myArray[i];
}
Also, you should remove the else if block from your code, because it's redundant (the first if statement checks for that condition):
else if(sumof3E < sum)
{
return false;
}
Alternatively, with the help of java 8 features, you can shorten your code into one line:
public static boolean sumThree(int [] myArray){
return Arrays.stream(myArray).limit(3).sum() < Arrays.stream(myArray).skip(3).sum();
}
note - with the alternative solution you won't get IndexOutOfBoundsException even if the array being passed in is empty.
There are two issues in your code:
1) You don't verify that the Array even has 3 elements before you index into it, which will potentially cause errors.
2) You're summing the entire array and comparing it to the sum of the first three elements... in your loop try initializing i = 3 in the loop initialization (assuming the array has at least 4 elements)
Pseudo code:
public static boolean sumThree(int [] myArray)
{
if (myArray.length < 4) { return false; }
var first = myArray[0] + myArray[1] + myArray[2];
var rest = 0;
for(int i = 3; i<myArray.length; i++) {
rest += myArray[i];
}
return first < rest;
}
the sum loop need to be altered to start from index 2 and else if is not required.
public static boolean sumThree(int[] myArray) {
int sum = 0;
for (int i = 3; i < myArray.length; i++) {
sum += myArray[i];
}
int sumof3E = myArray[0] + myArray[1] + myArray[2];
if (sum > sumof3E) {
return true;
}
else {
return false;
}
}
for clarity make a two loop then use the conditional operator or known as ternary operator for using thee if..else easily
int sum1=0;
int sum2=0;
for(int i=0;i<=2;++i)
{
sum1+=myArray[i];
}
for(int i=3;i<myArray.length;++i)
{
sum2+=myArray[i];
}
boolean myBool = (sum1>sum2)?false:true;
return myBool;
There is no need to keep going through the whole array at a time when first sum becomes less than sum of rest:
int sumf3 =0;
int sumRest=0;
for (int i = 0; i < myArray.length; i++)
{
if (i < 3){
sumf3 += myArray[i];
} else {
sumRest += myArray[i];
}
if(sumf3 < sumRest ){
return true;
}
}
return false;
P.S. and no need to check size of array before loop as well.
I'm working on this problem:
Consider the divisors of 30: 1,2,3,5,6,10,15,30.
It can be seen that for every divisor d of 30, d+30/d is prime.
Find the sum of all positive integers n not exceeding 100 000 000
such that for every divisor d of n, d+n/d is prime.
and I thought for sure I had it, but alas, it's apparently giving me the wrong answer (12094504411074).
I am fairly sure my sieve of Eratosthenes is working (but maybe not), so I think the problem is somewhere in my algorithm. It seems to get the right answer for n = 30 (1+2+6+10+22+30 = 71 - is this correct?), but as numbers get larger, it apparently stops working.
Here is my Java code:
import java.util.HashSet;
public class Generators {
static HashSet<Integer> hSet = new HashSet<Integer>();
public static void main(String[] args) {
// TODO Auto-generated method stub
int n = 100000000;
sieveErat(n + 1); //Fill a hashSet with prime numbers
System.out.println("Sieve complete");
int check = 0;
long sum = 3;
for(int i = 2; i <= n; i++){
int numDivisors = 0;
int numPrimeChecks = 0;
boolean done = false;
if(!hSet.contains(i+1)){ //i+1 must be a prime number for i to be prime generating
continue;
}
else{
for(int j = 2; j < i/2; j++){
if(i%j == 0){
numDivisors++;
check = j + i/j;
if(hSet.contains(check)){
done = true;
numPrimeChecks++;
}
}else{
break;
}
}
if(numPrimeChecks == numDivisors && done){
sum += i;
}
}
}
System.out.println(sum);
}
public static void sieveErat(int N){
boolean[] isPrime = new boolean[N + 1];
for (int i = 2; i <= N; i++) {
isPrime[i] = true;
//count++;
}
// mark non-primes <= N using Sieve of Eratosthenes
for (int i = 2; i*i <= N; i++) {
// if i is prime, then mark multiples of i as nonprime
// suffices to consider mutiples i, i+1, ..., N/i
if (isPrime[i]) {
for (int j = i; i*j <= N; j++) {
isPrime[i*j] = false;
// count--;
}
}
}
for(int i = 2; i < isPrime.length; i++){
if(isPrime[i]){
hSet.add(i);
}
}
// System.out.println(count);
}
}
The maths of your sieve looks fine to me. I hacked it around to use a BitSet which is much more space efficient. Is 5761455 primes below 100,000,000 correct?
Once I got your code working I got the same figure you get (12094504411075) what figure should you be getting?
I think this bit is wrong (I have changed the variable names to match the question for clarity)
for(int d = 2; d < Math.sqrt(n+3); d++) {
if (n % d == 0) {
numDivisors++;
int check = d + n / d;
if (primes.get(check)) {
// **** What does done mean??? ****
//done = true;
numPrimeChecks++;
} else {
// **** Added! Got a divisor that did not check. No point in going on.
break;
}
} else {
// **** Why break here??? ****
//break;
}
}
NB I have edited this code to reflect what we finally decided was a correct solution.
Why are you breaking out of the d loop as soon as you hit a d that does not divide n? Surely that cannot be right.
However, I think you can break out of the d loop when you have a divisor that does not check.
Also, what is your intended functionality of done? It seems to have no real function.
And, why do you start sum at 3?
Removing the break I now get the value 1739023853139. Is this correct?
Added
Here's my sieve. Identical to yours but builds a BitSet which is a much more efficient structure than a HashSet in this case:
public static BitSet sieveOfEratosthenes(int n) {
BitSet isPrime = new BitSet(n);
// Iniially all numbers are prime.
for (int i = 2; i <= n; i++) {
isPrime.set(i);
}
// mark non-primes <= N using Sieve of Eratosthenes
for (int i = 2; i * i <= n; i++) {
// if i is prime, then mark multiples of i as nonprime
// suffices to consider mutiples i, i+1, ..., N/i
if (isPrime.get(i)) {
for (int j = i; i * j <= n; j++) {
isPrime.clear(i * j);
}
}
}
//System.out.println("Found " + isPrime.cardinality() + " primes");
return isPrime;
}