Facing problem with the output of this code - java

My friend gave me this code and i cant seem to find the error in it. I am attaching the code below:
import java.util.*;
public class prg {
public static void main(String[] args) {
int n;
int count;
int a=0,b=1;
int c=0;
Scanner kb=new Scanner(System.in);
n=kb.nextInt();
int ar[]=new int[100];
ar[1] = 2;
for(int i=3;i<=n;i+=2)
{
count=0;
for (int j = 2; j < i ;j++ ) {
if (i % j == 0) {
count++;
break;
}
}
if(count==0)
ar[i]=i;
}
for(int i=0;i<=n;i+=2)
{
a = b;
b = c;
c = a + b;
ar[i]=c;
}
for(int i=0;i<14;i++)
System.out.print(ar[i]+" ");
}
}
So, the even index is storing the fibonacci series and the odd index is storing prime number.
Problem: the rest of the code is working fine but the 9th index of 'ar' array is printing 0 i dont know why and because of it the output is showing wrong.
Take input n as 14 and check the code please.
Thankyou in advance.
PS: i have solved this question in one other way so i request you to not give answers like 'try my method, its not efficient'. I just want to know what is going wrong at INDEX 9 of the array.
Edited: facing problem with the Prime Number loop.

When i is 9, your code correctly identifies that it is not a prime number, so count is not 0. This causes this line to not run:
ar[i]=i;
And then you increase i by 2 to check the next odd number. This means that you never set index 9 of the array to anything, so it remains at its default value - 0.
To fix this, you should introduce a new variable possiblePrime to keep track of which number you are checking. Increase this variable every iteration of the outer for loop, and increase i only when possiblePRime is prime. Also, change the above line to:
ar[i] = possiblePrime;

9 is not a prime number, so it sets nothing in the array. 0 is the default value so it gets printed.

Related

Problem with logic of this pattern problem

Here is the question. I have to print this pattern eg For n = 5
For n = 5
****1
***232
**34543
*4567654
567898765
I have written logic for this problem but I am not able to solve it.
I can't make the last pattern print i.e. the decrease one 2 4,3 5,4
Here's my pattern For n = 5
****1
***232
**34544
*4567666
567898888
Can anyone help me out and tell what's wrong with my logic. How to fix it
My code down below
import java.util.Scanner;
import java.lang.*;
public class Main {
public static void main(String[] args) {
solve();
}
public static void solve(){
int n;
Scanner obj = new Scanner(System.in);
n = obj.nextInt();
for(int row =1;row<=n;row++){
int ans1 = row;
int spaces =1;
for( spaces = 1;spaces<=n-row;spaces++){
System.out.print("*");
}
for (int pattern01 = 1; pattern01<=row;pattern01++){
System.out.print(ans1);
ans1 = ans1 +1;
}
for ( int pattern2 = 1 ; pattern2<=row-1; pattern2++){
ans1= 2*row-2;
System.out.print(ans1);
ans1--;
}
System.out.println();
}
}
}
The issue you are having is that you are not decrementing 'ans1' correctly. If you are not sure how to use the debugger then observe your output through the console with print-out statements. Specifically the 3rd loop when 'ans1' is supposed to count backwards. Also, keep in mind the value of 'ans1' after you exit the second for-loop.
This is your second loop when you start to count up from row number variable.
You increment 'ans1' by 1 each iteration.
for (int pattern01 = 1; pattern01 <= row;pattern01++) {
System.out.print(ans1);
ans1 = ans1 + 1;
}
One thing to consider is that you are incrementing 'ans1' and what is the value of it before you enter your third loop to decrement? You need to do something here before you enter the loop and start printing.
Also, in your third loop you are not decrementing correctly. You should be counting backwards, or rather just decrementing by 1.
for(int pattern2 = 1;pattern2 <= row-1; pattern2++){
ans1= 2*row-2; // Your focus should be here, does this look right? Do you need it?
System.out.print(ans1); // You should decrement first and then print
ans1--; // this is correct, but in the wrong spot
}
I know you can pull it off :) You got this.

Multiply numbers for loop java returning 0

I'm trying to take a number(n) and multiply it by every number before it, enter 4 you get (1x2x3x4) = 24. My code returns a 0. I have an addition just like this that works. Any ideas?
public static int multiplyTooNum()
{
Scanner myIn = new Scanner(System.in);
int n;
System.out.println("Please enter a number");
n = myIn.nextInt();
myIn.nextLine();
int sum = 0;
for (int i=0; i<n; i++)
{
sum = sum * i;
}
int result = sum*n;
System.out.println(result);
myIn.close();
return result;
}
In multiplication, the accumulated variable is not called sum. It is called product. The word sum is only used in the context of addition.
Now, on with your problem:
If you remember your elementary school mathematics, anything multiplied by zero gives zero.
That's why you are receiving a zero in the end.
So, in order to fix this, you have to initialize your product with 1 instead of 0, and then make your for loop start counting from index 1 instead of 0.
for (int i=0; i<n; i++)
{
sum = sum * i;
}
Issue is in this part, you start i from 0, so each time the sum get's 0 and it will be multiplied again. I suggest you to learn debugging and step over in loops to pinpoint the issues.

Prime Numbers Array in Java

I want to return an array that displays all the prime numbers within a certain range from 0 till whatever number I enter.
For the range from 0 to 5 I would like the array returned with [2,3,5]. Within the task I was told by my professor that I should fill the whole array with 0 before replacing those 0 wih prime numbers later.
Currently my code does not return the correct array as I do not seem to access the next location in the array but seem to always assign the value to the first location in the array.
My current result array is not [2,3,5] but [5,0,0,0,0].
Any help would be greatly appreciated.
public static int[] generierePrimzahlen(int bis){
int [] myAry = new int[bis];
Arrays.fill(myAry,0);
for(int i=0;i<myAry.length;i++){
for (int nextprime=1; nextprime < bis; nextprime++){
int counter = 0;
// System.out.println(nextprime);
if (istPrimzahl(nextprime)){
myAry[counter] = nextprime;
counter++;
}
}
System.out.print(myAry[i]+" ");
}
return myAry;
}
PS: I have a functioning method (istPrimzahl), which checks if a certain number is a prime number or not.
The problem is that your counter is in the wrong scope.
so instead of incrementing. on every iteration of the first for loop, you declare a new counter. so that it is 0 at the time u assign the prime number to the array.
public static int[] generierePrimzahlen(int bis){
int [] myAry = new int[bis];
// Arrays.fill(myAry,0); // no need, this is already been done at initialization
for(int i=0;i<myAry.length;i++){
int counter = 0;
// adding <= 'nextprime <= bis;' to check also the last number in the range
for (int nextprime=1; nextprime <= bis; nextprime++){
// int counter = 0; wrong scope
// System.out.println(nextprime);
if (istPrimzahl(nextprime)){
myAry[counter] = nextprime;
counter++;
}
}
if(myAry[0] != 0) // to get rid of displaying Zeros
System.out.print(myAry[i]+" ");
}
return myAry;
}
Put below line outside both for loop. That will work.
Reason for issue is - you are resetting the counter while entering the for loop.
int counter = 0;
ArrayList will be a better choice than array. However if using array is another school requirement, then what you have done:
int[] myAry = new int[size];
will already set all elements to zeroes.
There is also no need to use 2 loops for this. Just:
Loop through from 1 to n
if current number is prime, set it to array of current index
idx++
I do not seem to access the next location in the array but seem to always assign the value to the first location in the array.
That is because you are setting your counter variable back to zero in every iteration. You should declare it outside your loop.
Example:
int idx = 0; //place this outside the loop
for(int i=1; i<=n; i++)
if(isPrime(i))
myAry[idx++] = i;

Why isn't my code returning the "maximum" number of consecutive 1's for the specific input "524275"?

I'm trying to solve HackerRank Day Of Code 10.
In short, the task is to find the maximum number of consecutive 1's in the binary representation of a decimal number. In my code I've tried to use two variables: count and hold. count increases by 1 whenever the current position of the string and the previous position are both 1. Whenever the i'th position is 0, count 's value is assigned to the variable hold. In the following iterations if ever the value of count exceeds that of hold then the value of count is assigned to hold. In this way the maximum number of consecutive 1's is stored in hold. Finally I'm printing the value of hold.
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter decimal number");
int n = in.nextInt();
String binary = Integer.toString(n,2);
int count=1;
int hold=0;
if(binary.equals("0"))
System.out.println(0);
else
{
for(int i=0;i<binary.length();i++)
{
if(i==0){}
else if(binary.charAt(i-1)=='1' && binary.charAt(i)=='1')
{
count++;
}
if(count>hold)
hold=count;
if(binary.charAt(i)=='0')
{
hold=count;
count=1;
}
}
System.out.println(hold);
}
}
}
My code isn't working for the sample input "524275" which converts to "1111111111111110011" in binary. The output comes out to be 2 which is strange. my code is written such that the "maximum" number of consecutive 1's are returned. Where did I go wrong? I tried dry running the code mentally but can't spot the mistake yet.
After processing the first 15 ones in with the for loop, hold will actually have the value 15. Then you meet the first zero, and if(binary.charAt(i)=='0') { hold=count; count=1; } will reset count to 1. But then you immediately find another zero, and the same code if(binary.charAt(i)=='0') { hold=count; count=1; } stores 1 in hold and you loose the information 15.
An easy solution is just to remove the line hold=count; in this line. You already set hold three lines above. (And correctly, because you only do it if count is bigger then the previous best value.
The approach is quite complicated. If you want an easier approach. The code should be pretty self-explanatory.
int current_consecutive_ones = 0;
int best_consecutive_ones = 0;
for(int i = 0; i < binary.length(); i++)
{
if (binary.charAt(i) == '1')
current_consecutive_ones++;
else
current_consecutive_ones = 0;
if (current_consecutive_ones > best_consecutive_ones)
best_consecutive_ones = current_consecutive_ones;
}
System.out.println(best_consecutive_ones);

How to recall a function, Sieve of Eratosthenes

I'm trying to write code that will work out prime numbers using the sieve of Eratosthenes. I have to include a function that will take in a number and cross of all of the multiples of that number. For testing I set the first number to be 2 and the second as 3. It works for the first number but never for the second(no matter the order of the numbers i.e if I put 3 into the function first). I know there are other completed sieve of Eratosthenes out there but I wanted to try and do it in the way that I thought of first.
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("Which number would you like to calculate up to?");
int n = input.nextInt();
input.close();
int x = 0;
int newNumber = 2;
int numbers[] = new int[n];
while(newNumber <= n){
numbers[x] = newNumber;
x++;
newNumber++;
}
int currentNumber = 2;
int finalNumber[] = markOfMultiples(n, numbers, currentNumber);
for(int y = 0;y < n-1;y++){
System.out.print(finalNumber[y] + ", ");
}
currentNumber = 3;
int secondNumber[] = markOfMultiples(n, numbers, currentNumber);
for(int y = 0;y < n-1;y++){
System.out.println(secondNumber[y]);
}
}
public static int[] markOfMultiples(int n, int numbers[], int currentNumber){
int originalNumber = currentNumber;
while(currentNumber<n){
currentNumber = currentNumber + originalNumber;
int count2 = 0;
while(currentNumber != numbers[count2] && currentNumber<=n && count2<n){
count2++;
}
numbers[count2] = 0;
}
return numbers;
}
The error I'm getting is: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 20
at sieveOfEratosthenes.sieveOfEratosthenes.markOfMultiples(sieveOfEratosthenes.java:46)
at sieveOfEratosthenes.sieveOfEratosthenes.main(sieveOfEratosthenes.java:28)
Line 28 is when I recall the function:int secondNumber[] = markOfMultiples(n, numbers, currentNumber);
And line 46 is while(currentNumber != numbers[count2] && currentNumber<=n && count2<20){
Any help would be much appreciated. How do I keep on calling the function?
p.s. Please excuse the variable names as I'll be changing them when I get the program working.
If you want to get this approach working, you can do the fix advised by #Thierry to check count2 < n first in your while loop and then also surround the line
numbers[count2] = 0
with an if clause to check count2 is not beyond the end of the index. e.g.
if (count2 < n) {
numbers[count2] = 0;
}
Your final challenge is how you call your markOfMultiples() function enough times when n gets a bit larger. It's not a problem with your fundamental approach - you can definitely do it and your approach will work well and have acceptable performance for low-ish numbers (say up to 10000).
However
I realise this is an assignment and you want to do it your way, but there are a few features of your approach which you might want to consider - maybe after you've got it working.
Readability - is it going to be easy for someone looking at (marking) your code to understand what it's doing and verify that it will do the right thing for all values of n?
Try not to repeat yourself - for instance consider where you fill your numbers array:
while(newNumber <= n){
numbers[x] = newNumber;
x++;
newNumber++;
}
Will x ever be different to newNumber? Did you need both variables? This sort or repetition occurs elsewhere in your code - the principle to stick to is known as DRY (Don't Repeat Yourself)
Is there an easier way to move the index on originalNumber places in your markOfMultiples() method? (HINT: yes, there is)
Do you really need the actual numbers in the numbers[] array? You're going to end up with a lot of zeros and the primes left as integer values if you work out how to call your markOfMultiples repeatedly for high values of n. Would an array of 1s and 0s (or trues and falses) be enough if you used the array index to give you the prime number?
You need to test if count2 < n BEFORE access to numbers[count2]:
while(count2 < n && currentNumber != numbers[count2] && currentNumber<= n){
count2++;
}

Categories