Understanding a modified variant of Sieve of Eratosthenes algorithm [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I came across this algorithm on a coding site (There was no author's information) which counts all prime numbers less than a given limit. It looks very similar to SoE algorithm but it is different in the way it counts the primes:
public int countPrimes(int n) {
if (n < 3) return 0;
boolean[] s = new boolean[n];
int c = n / 2;
for (int i = 3; i < Math.sqrt(n); i += 2) {
if (s[i]) continue;
for (int j = i * i; j < n; j += 2 * i) {
if (!s[j]) {
c--;
s[j] = true;
}
}
}
return c;
}
It sets the initial count to half the limit then decrement it, but I can not seem to understand why does this work. Can anyone please explain?

First of all, the boolean array s represents SoE.
The first loop iterates odd numbers from 3 to sqrt(n) (Because all even except 2 is not prime).
At the 6th line, If i is already in the s, continue to next odd number. If not, add all multiple of i that is less or equal to n to s in the second loop.
In addition, the second loop starts from i*i because all multiple of i smaller than i*i are already checked in prior loops.

The count is initialized to n/2 because all even numbers (except 2) are not primes.
And then the loop below can start checking from multiples of 3.
If a new non-prime is found (!s[j]), the count of primes (c) is decreased.

Related

Assistance with array lab [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am in a intro to Java class. I seem to be having trouble figuring out the algorithm for how i want to go about this.
Currently I need to create and application that generates the number to store in an array element by summing its index and the individual digits of the index. For example, the element with index 17 should be stored as 25... (17+1+7=25) and an element with index 2 would store as 4 (2+0+2=4). I need the program to have 101 elements and then display each value.
I seem to be having trouble figuring out the algorithm for how i want to go about this. Any assistance in the matter would be greatly appreciated.
Thanks in advance. I currently am still researching this matter and am still learning to code so please bear with me.
This is the updated code that I have come up with so far
import java.util.Random;
public class Java_Lab_4 {
public static void main(String[] args) {
int size = 101;
int max = 101;
int[] array = new int[size];
int loop = 0;
Random generator = new Random();
//Write a loop that generates 101 integers
//Store them in the array using generator.nestInt(max);
generator.nextInt(max);
for (int i = 0; i<101; i++)
{
generator.nextInt(max);
}
}
There are surely many ways to achieve this, but the easiest would be repeated division by 10 (another way would be modular arithmetic, taking the index modulo 10).
This means that you would arrive at something like the following algorithm:
int n = i; // i is the index of the current item
while (n > 0) {
int x = n;
if (x > 10) { // we need to deal with the case where i is small
x = n / 10;
}
while (x > 10) { // necessary because we may be dealing with an index > 100
x = x / 10;
} // at this point we have the first digit of the index
a[i] += x; // add this digit to a[i]
n = n / 10; // get rid of the above digit in the calculation. Note that if n < 10, integer division means that n / 10 == 0
} // at the end of this loop, we have added all digits of i to a[i]
a[i] += i; / now we only need to add the index value itself
There are many ways to solve this, and this is a very straightforward and basic approach. I've added ample comments, but please try to work through the code to understand why this works rather than just copying it.
Without posting complete code -- because this is an assignment -- here are some things to consider:
array[a] = a + a;
would give you the solution for indices where a < 10. For two/three digit indices, you need to extract the digits with for example
int nthDigit = Integer.parseInt( // Finally, converts the single-char String to an int
String.valueOf( // converts the char matching the digit to a String
String.valueOf(a).charAt(n))); // converts 'a' first to a String and
// then takes its 'n'th character
where n is 0, 1 or 2. The values of these would then need to be added to the value of the index (a).

Fibbonacci sequence using for loop java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Can someone explain to me how to store the previous two fibbonnaci numbers it would help alot in this problem.
public static void main(String[] args) {
int k = 0;
for (int x = 1; x < 13; x++) {
if (k > 2) {
k = (k - 1) + (k - 2);
}
System.out.print(k+" ");
k++;
}
}
when you got number 5 as the printed out put you will set k++ , that will make k=6.
after that k = (k - 1) + (k - 2); output k = (6-1)+(6-2) = 5+4 = 9 , (note : the next should be 8 so your algorithm is wrong)
You have mistaken the Idea of Fibonacci numbers.
the nth Fibonacci number is equal to the sum of previous two Fibonacci numbers. not to the (Fn-1)+(Fn-2)
Edited :
So as you can see if we know the first 2 Fibonacci numbers we can calculate the third by adding those two. and the fourth one will be the summation of second one and third one and it goes ..... to n.
Okay here is a way that you don't need a recursive approach ( you need to store the found Fibonacci numbers in an Array)
okay assume you want to find first n Fibonacci numbers. then create an array of size n and set first and second elements to one (1) since first two Fibonacci numbers are 1 and 1. now loop through the array from 2 to n. at each iteration add the previous two element to the next element.
go through the code. you will find it very easy to do.
public static void fib(int n){
int Fibonacci [] = new int[n];
Fibonacci [0]=1;
Fibonacci [1]=1;
for (int i = 2; i < n; i++) {
Fibonacci [i]=Fibonacci [i-1]+Fibonacci [i-2];
}
System.out.println(Arrays.toString(Fibonacci ));
}

Understanding why my code reverses a number [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
So I came across this code on the web and I am trying to wrap my head around how the code is reversing the number order. Can someone help me out? Additionally, is there a way I can change the while loop into a for loop? I don't see an increment so the code is throwing me off just a little.
import java.util.Scanner;
class Challenge{
public static void main(String args[]){
///{write you code here
int n, reverse = 0;
System.out.println("Enter the number to reverse");
Scanner in = new Scanner(System.in);
n = in.nextInt();
while( n != 0 )
{
reverse = reverse * 10;
reverse = reverse + n%10;
n = n/10;
}
///}
System.out.println("Reverse is :"+reverse);
}
}
Say your number is 123. The first time through the loop, reverse starts off at 0, so this line, does nothing.
reverse = reverse * 10;
This line, however, takes the last digit of n.
reverse = reverse + n%10;
So now, reverse is 3.
The last line, divides n by 10, discarding any remainder
n = n/10;
So now n is 12.
The second pass through the loop, the following happens:
reverse = reverse * 10;
reverse is now 30.
reverse = reverse + n%10;
reverse is now 32.
n = n/10;
n is now 1.
Last time through the loop:
reverse = reverse * 10;
reverse is now 320.
reverse = reverse + n%10;
reverse is now 321.
n = n/10;
n is now 0.

How can I locate an index given the following constraints? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Given an array of n integers A[0…n−1], such that ∀i,0≤i≤n, we have that |A[i]−A[i+1]|≤1, and if A[0]=x, A[n−1]=y, we have that x<y. Locate the index j such that A[j]=z, for a given value of z, x≤ z ≤y
I dont understand the problem. I've been stuck on it for 4 days. Any idea of how to approach it with binary search, exponential search or interpolation search recursively? We are given an element z find the index j such that a [j] = z (a j) am i right?.
This:
| A[i]−A[i+1] | ≤ 1
means that each element in your array will be at most one different(-ve or +ve). It then follows that the closest index that can contain z from the current is |A[cur] - z| spaces away.
So, what you do is start with j=0, and figure it out for each step. Jump that many spaces, and check again. Eventually you'll find z or reach the end.
public static int findZ(int[] a, int z){
int j = 0;
while(j < a.length){
if(a[j] == z)
return j
j += Math.abs(a[j] - z);
}
return -1;
}
This isn't a binary or exponential search, and it's not recursive, but it's simple and gets the job done. It works as a one-sided interpolation search. See below for the two-way method. You can turn it into a recursive function, but that should be straightforward and I'll leave that to you.
It runs in O(n), where your worst case performance is going to be on something like {0,0,0,0,1}, where it can only jump one step, and turns into a straight linear search.
Best case will be ordered, distinct members like {0,1,2,3,4,5}, where it will only perform one jump.
Edit:
In the interests of making this more "interpolation search-like", let's move both the upper and lower bounds at the same time. The same logic applies for both ends:
public static int findZ(int[] a, int z){
int j = 0;
int k = a.length - 1;
while(j <= k){
if(a[j] == z)
return j
if(a[k] == z)
return k;
j += Math.abs(a[j] - z);
k -= Math.abs(a[k] - z);
}
return -1;
}
It still ends up as O(n) overall worse case, but this is normal for an interpolation search.
Now your worst case is more like {0,0,0,1,0,0,0}, and your best is like {0,1,2,3,2,1,0}.

The value of the loop counter of a for loop is one larger than I expect after exit from the loop [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a simple for loop, which lets the loop counter, i go up to 5.
int i;
double n = 1 / 2;
for (i = 2; i <= 5; i++) {
n = n + 1.0 / i;
}
System.out.print(i);
So I expect the value of the counter to be 5 after the loop finishes. But the value is 6, nit 5. Why is that?
Thanks
Because you are incrementing i value as i++ in for{..} loop
for (i = 2; i <= 5; i++)
^ here
In for loop after checking the condition, body part will be executed
after that increment or decrement will be done
Process will be
<----
1step 2step 4step
for (i = 2; i <= 5; i++){
/*body part*/
3step
}
After 4th step it will moves to check 2nd step i.e. condition part
So thats why it prints the i value as
6
The for loop:
for (i = 2; i <= 5; i++) {
// code
}
which has condition i <= 5 and the condition will be false when i = 6 and the loop breaks, goes to the print line.
Thanks for reminding me my first time programming experience, When I used to write a code a = 5 and printed it to see what it shows in the console. :)
The i++ is the same as saying i = i + 1. In this case you can also use ++i and get the same result.

Categories

Resources