Java - Why won't my prime number program print the last number? - java

I'm supposed to write a program for a Java Intro class that lists the prime numbers up to the number a user inputs. However, with the code I have, if the user inputs a prime number, my program won't list back that number, even though it's supposed to do so when it's prime. Could someone give me a hint as to why it's not working?
int userNum=kbd.nextInt();
if (userNum<2){
System.out.println("Not a valid number.");
System.exit(1);
}
System.out.println("The prime numbers up to your integer are:");
for (int num1 = 2; num1<userNum; num1++) {
boolean prime = true;
for (int num2 = 2; num2 < num1; num2++) {
if (num1 % num2 == 0) {
prime = false;
break;
}
}
// Prints the number if it's prime.
if (prime) {
System.out.print(num1 + " ");
}
}
For example, when I input "19," the program prints all prime numbers up to and including "17."
Thanks!

You need num1 to take the value userNum as the last value to check.
Therefore, you need to replace num1 < userNum with num1 <= userNum.

Your loop has a condition of num1 < userNum. This means that it allows all numbers below userNum. What you appear to want is all numbers below and including userNum, so you want num1 <= userNum.
The start of your loop would thus be this:
for (int num1 = 2; num1 <= userNum; num1++) {

Change this
num1<userNum
to
num1<=userNum
At the moment you stop before the two numbers are equal in your for loop.

Change the end condition of your for statement to num1<=userNum.

Related

What is the time and space complexity of this code? I'm very confused on this subject so I am asking

This is my code, it is a russian peasant multiplication algorithm. I find the time and space complexity very confusing so I needed some help.
This is also for java language
Thank you.
int num1 = Integer.parseInt(jTextField1.getText());
int num2 = Integer.parseInt(jTextField2.getText());
int res=0;
// While second number doesn't become 1
while (num2 > 0)
{
// If second number becomes odd,
// add the first number to result
if ((num2 & 1) != 0)
res = res + num1;
// Double the first number
// and halve the second number
num1 = num1 << 1;
num2 = num2 >> 1;
}
jTextField3.setText(String.valueOf(res));
}
The loop continues to execute provided that num2 be greater than zero. After each iteration of the loop, num2 is halved. This means that the loop will execute log_2(num2) times. So, assuming num2 be represented by N, we can say that the complexity of this loop is log_2(N).

Greatest Common Divisor Program Only Printing 1

I'm making a program where you put in two integers, and the program finds the greatest common divisor between the two numbers.
It runs fine, except it prints "1" as the GCD, even when the two numbers should have a different GCD. (Example: 4 & 64. GCD should be 4, but 1 still gets printed.) I can't figure out what's wrong with my code.
For those who want to answer using one method instead, I can't: It's an assignment that requires me to use two different methods in the same program. Please help?
Thanks for reading, and have a good week.
Here my code:
import java.util.Scanner;
public class greatestCommonDivisorMethod {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
//Number entry prompts
System.out.print("Please enter first integer: ");
int num1 = input.nextInt();
System.out.print("Please enter second integer: ");
int num2 = input.nextInt();
//Result printed
System.out.println("The greatest common divisor of " +num1+ " and " +num2+ " is " +gcd(num1, num2)+".");
}
public static int gcd(int num1, int num2) {
int gcd = 1;
int k = 2;
while (num1 <= k && k <= num2)
{
if (num1 % k == 0 && num2 % k == 0)
gcd = k;
k++;
}
return gcd;
}
}
while (num1 <= k && k <= num2)
{
if (num1 % k == 0 && num2 % k == 0)
gcd = k;
k++;
}
It looks like you accidentally switched num1 and k in your while loop.
The while condition should probably have k<=num1 instead of num1<=k
Assign your return to a variable then print it
int answer = gcd(num1, num2);
then when printing cast to String or use toString method.
System.out.println("The greatest common divisor of " +answer.toString());

Is The First Number a Multiple of the Second Number

I am writing a program that asks the user to input two integers a total of ten separate times.
Next the program needs to evaluate whether or not the first integer is a multiple of the second integer.
If the first is a multiple of the second then the program should print out "true," if it is not then it should print out "false."
Here is my code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int counter = 0; // Initializes the counter
System.out.printf("Enter first integer: "); // asks the user for the first integer
int number1 = input.nextInt(); // stores users input for the first integer
System.out.printf("Enter second integer: "); // asks the user for the second integer
int number2 = input.nextInt(); // stores the users input for the second integer
while (counter <= 10) // starts a loop that goes to 10
{
if (number1 & number2 == 0) // checks to see if number1 is a multiple of number2
System.out.print("true"); // if so then print out "true"
else
System.out.print("false"); // otherwise print out "false"
}
} // end class
Somewhere along the line my code is breaking. Is there anyone who can help, or at least point me in the right direction?
You need to read two inputs 10 times. And test if number1 is a multiple of number2. Something like
public static void main(String str[]) throws IOException {
Scanner input = new Scanner(System.in);
for (int counter = 0; counter < 10; counter++) {
System.out.printf("Enter first integer for counter %d: ", counter);
int number1 = input.nextInt();
System.out.printf("Enter second integer for counter %d: ", counter);
int number2 = input.nextInt();
// Since you want to print true if number1 is a multiple of number2.
System.out.println(number1 % number2 == 0);
}
}
& is the bitwise logical AND function. I'm quite sure that won't do what you want it to do. Seems like you want the MODULO operator, %.
E.g. Use number1 % number2. instead of number1 & number2
while (counter <= 10) // starts a loop that goes to 10
{
if (number1 % number2 == 0) // checks to see if number1 is a multiple of number2
System.out.print("true"); // if so then print out "true"
else
System.out.print("false"); // otherwise print out "false"
}

How to input different numbers with Java

The question is to Write a program that sorts three integers. The integers are entered from the input dialogs and stored in variables num1, num2, and num3, respectively. The program sorts the numbers so that num1 <= num2 <= num3.
actually I do that but the result is available only to 1 ,2 and 3 numbers !
When I enter any different number it doesn't show me the result I want it !
here is my code..
import javax.swing.JOptionPane;
public class number order {
public static void main(String[] args) {
int num1;
int num2;
int num3;
String n = JOptionPane.showInputDialog(null, "input NUM 1 " );
num1 = Integer.parseInt(n);
String u = JOptionPane.showInputDialog(null, "input NUM 2 " );
num2 = Integer.parseInt(u);
String m = JOptionPane.showInputDialog(null, "input NUM 3 " );
num3 = Integer.parseInt(m);
if (num1<=num2&& num2<=num3)
System.out.println( num1+"<="+ num2+"<="+num3 );
if(num2<=num1&&num1<=num3)
System.out.println(num2+"<="+num1+"<="+num3);
if (num3<=num1&&num1<=num2)
System.out.println(num3+"<="+num1+"<="+num2);
// TODO code application logic here
}
}
The problem is that you check only three out of six possible arrangements of those three numbers. Also note that, even for those three, you are not actually sorting the numbers, but only printing them in sorted order, i.e., you are never reassigning the variables num1, num2, and num3.
Just as an alternative to checking all the possible arrangements of the three numbers or implementing a full sorting algorithm, you can also compare and swap pairs of numbers. This way, you get away with far fewer comparisons while still being able to sort all permutations of three numbers.
if num1 > num2, swap num1 and num2
if num2 > num3, swap num2 and num3
if num1 > num2, swap num1 and num2 again
After those three swaps, the numbers are in sorted order.
Of course, if you have more than three numbers this gets impractical, and you should rather implement a full sorting algorithm (for exercise) or go with one of the builtins, like Arrays.sort (for real life).
You haven't checked all cases:
1 < 2 < 3
1 < 3 < 2
2 < 1 < 3
2 < 3 < 1
3 < 1 < 2
3 < 2 < 1
However to check all case like that is not to useful.
an sorted array would be more easy:
int arr[3]={num1,num2,num3}
java.utils.Arrays.sort(arr);
println(arr[0] + "<=" + arr[1] + "<=" + arr[2]);
int[] all = new int[]();
num1 = Integer.parseInt(n);
all[0] = num1;
num2 = Integer.parseInt(u);
all[1] = num1;
num3 = Integer.parseInt(m);
all[2] = num1;
for(int i=0; i <all.length ;i++){
if(i!=0 && all[i]< all[i-1]){
temp = all[i-1];
all[i-1] = all[i];
all[i] = temp;
}
}
all will have sorted array
or more simply
2 steps
1)add all to a array.
2) call Arrays.sort(array)
how about
int min = min(min(num1,num2),num3);
int max = max(max(num1,num2),num3);
int mid = num1 + num2 + num3 - min - max;
System.out.println(min+"<="+mid+"<="+max);
if(num1 < num2){ if(num3 < num1) System.out.println("num2 > num1 > num3");}
else{ if(num2 < num3) System.out.println("num3 > num2 > num1"); else System.out.println("num1 > num2 > num3");}
Sort in descending order.
Hope it helps.

JAVA do-while Loop doubles the output value

The following code outputs the sum, average, count of positive/negative numbers, count of all numbers correctly when ran first time. Because it loops, hence, the output remains on the console prompting user to enter numbers again. At this time, only sum shows the correct output, other values doubles. Please help me in fixing the loop. Thanks!
public class Test {
public static void main(String[] args) {
long n;
int count=0;
float average;
int positive=0;
int negative =0;
Scanner in = new Scanner(System.in);
do {
System.out.print("Enter a positive or negative integers: ");
n = in.nextLong();
if (n == 0){
System.out.println("Integers you've entered is invalid. Please re-launch the Program.");
}
else
{
int sum=0;
do
{
//Find sum of the integers entered.
sum += n %10;
n /= 10;
//Count number of integers entered.
count++;
//Find average of the numbers
average = sum / count;
//Find a count of positive and negative numbers.
if(n < negative){
negative++;
}
else{
positive++;
}
} while (n != 0);
n = sum;
System.out.println("The Sum of the numbers: " + sum);
System.out.println("The Average of the numbers: " + average);
System.out.println("Positive numbers are: " + positive);
System.out.println("Negative numbers are: " + negative);
System.out.println("The count of all numbers: " +count);
}
} while(n != 0);
}
}
It would make sense that sum is the only one that outputs correctly; It's the only value you initialize every iteration of your outer loop.
the values count, positive, and negative aren't re-initialized each iteration, so when you begin the next iteration of your outer loop, they will start from wherever they printed as.
you might want to initialize them again every time you run the loop.
You never reinitialize your variables before entering in your do while loop for a second time.
So
else
{
int sum=0;
do
{
Should be
else
{
int sum=0;
count=0;
average=0.0f;
positive=0;
negative =0;
do
{

Categories

Resources