This program checks if a user's input number is prime.
My problem is in the if statement. For some reason the Boolean is never switched. If the number is prime, it will just give both results.
What am I missing?
import java.util.Scanner;
public class Prime
{
public static void main(String[] args)
{
System.out.println("Enter a number to check if it is prime:");
Scanner kb = new Scanner(System.in);
int n = kb.nextInt();
boolean more = true;
do
{
for (int i = 2; i <= n; i++)
{
if (n <=1 || n%i==0)
{
System.out.println(n + " is not prime");
more = false;
}
}
}
while (more);
System.out.println(n + " is prime");
}
}
Remove the print which is inside if() and use the below code after the do while loop
if(more)
System.out.println(n + " is prime");
else
System.out.println(n + " is not prime");
and also you dont need a do while loop remove it.Complete Code
System.out.println("Enter a number to check if it is prime:");
Scanner kb = new Scanner(System. in );
int n = kb.nextInt();
boolean more = true;
for (int i = 2; i <= n / 2; i++) {
if (n <= 1 || n % i == 0) {
more = false;
break;
}
}
if (more) System.out.println(n + " is prime");
else System.out.println(n + " is not prime");
Demo
It's possible to check prime numbers with few lines using a for loop. It's better for performance.
Code to check prime numbers:
boolean isPrime = true;
for (int i = 2; i < n && isPrime; i++) {
isPrime = !(n % i == 0);
}
Full class according to your example:
import java.util.Scanner;
public class Prime {
public static void main(String[] args) {
System.out.println("Enter a number to check if it is prime:");
Scanner kb = new Scanner(System.in);
int n = kb.nextInt();
boolean isPrime = true;
for (int i = 2; i < n && isPrime; i++) {
isPrime = !(n % i == 0);
}
System.out.println(n + " is prime - " + isPrime);
}
}
Try this:
public static void main(String[] args) {
System.out.println("Enter a number to check if it is prime:");
Scanner kb = new Scanner(System.in);
int n = kb.nextInt();
boolean prime = true;
for (int i = 2; i <n; i++)
{
if (n <=1 || n%i==0)
{
prime = false;
break;
}
}
if(prime)
{
System.out.println(n + " is prime");
}
else
{
System.out.println("Not prime");
}
}
The following logic is working. Please try this.
int count=0;
for(i=2;i<=n/2;++i)
{
if(n%i==0)
{
count=1;
break;
}
}
if (count==0)
System.out.println(i+" is a prime number.");
else
System.out.println(i+" is not a prime number.");
If the count got increased, the given number is divisible by some other numbers. Or else It should be a prime number.
Thank you...
You don't need to check all the way up to n, just up to the square root. which if you calculate before should make your loop take less iterations and be faster.
Try this code with simple for loop.
boolean isPrime(int n) {
for(int i=2;i<n;i++) {
if(n%i==0)
return false;
}
return true;
}
Try this:
System.out.println("Enter a number to check if it is prime:");
Scanner kb = new Scanner(System.in);
int n = kb.nextInt();
boolean isPrime = true;
if (n < 1)
isPrime = false;
else
for(int i = 2; 2 * i < n; i++) {
if (n % i == 0) {
isPrime = false;
break;
}
}
System.out.println( n + " is " + (isPrime? "" : "not ") + "prime");
Related
I was making an Armstrong number checker not for only 3 digits numbers for which I used Math.pow() method but after using it the if else statement is not working also when the condition is true.
Here is the code:
import java.util.Scanner;
import java.lang.Math;
class Main {
////////////////////////////////////////////
////////////////////////////////////////////
public static void main(String args[])
{
System.out.println("Hello world!");
Scanner sc = new
Scanner(System.in);
int num = sc.nextInt();
int numc = num ;
double rem = 0;
double cu = 0;
int val = 0;
int val2 = 0;
while(num != 0){
rem = num%10;
while(numc != 0){
numc /=10;
int i = 0;
i++;
val2 += i;
}
cu = Math.pow(rem,val2 );
val += cu;
num /= 10;
}
if(val == numc){
System.out.println("Yes its a "+val2+" Armstrong number because its returning " + val+"after Calculations ");
}
else{
System.out.println("No its not a "+val2+" digit Armstrong number because its returning " + val +" after Calculations ");
}
}
}
///////////////////////////////////////////
And this is the Compilation of my code:
if(val == numc){ - This if part is the root cause of your problem . you are dividing numc by 10 for calculations . So at the end it will become 0 . so you will be checking if val == 0 which goes to the else loop.
So I would suggest to assign the input from the user to another variable which you can use for checking the final if - else part.
Like int input = num and at the end if(val==input){ . This would resolve your issue.
The num and numc become zero due to "/= 10" operation. Hence the if condition fails.
Also you need not compute the length of integer every time.
Don't have the reputation to comment hence giving a full fledged solution.
Following is my solution to your problem.
All the best!
import java.util.Scanner;
import java.lang.Math;
class Main {
////////////////////////////////////////////
////////////////////////////////////////////
public static void main(String args[]) {
System.out.println("Hello world!\n");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int numc = num;
double rem = 0;
double cu = 0;
int val = 0;
int val2 = countNumOfDigits(num);
while (num != 0) {
rem = num % 10;
cu = Math.pow(rem, val2);
val += cu;
num /= 10;
}
if (val == numc) {
System.out.println("Yes its a " + val2 + " digit Armstrong number because its returning " + val
+ "after Calculations ");
} else {
System.out.println("No its not a " + val2 + " digit Armstrong number because its returning " + val
+ " after Calculations ");
}
}
private static int countNumOfDigits(int number) {
if (number < 100000) {
if (number < 100) {
if (number < 10) {
return 1;
} else {
return 2;
}
} else {
if (number < 1000) {
return 3;
} else {
if (number < 10000) {
return 4;
} else {
return 5;
}
}
}
} else {
if (number < 10000000) {
if (number < 1000000) {
return 6;
} else {
return 7;
}
} else {
if (number < 100000000) {
return 8;
} else {
if (number < 1000000000) {
return 9;
} else {
return 10;
}
}
}
}
}
}
public class PrimeNumbers {
public static void main(String[] args) {
int num = 6;
boolean isPrime = true;
for (int i = 2; i <= num - i; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
int nextPrime = num++;
{
while (isPrime = false) {
}
if (isPrime)
System.out.println("Is a prime number");
else
System.out.println("Is not a prime number" + "the next prime number is" + nextPrime(num));
}
}
}
I have tried to code in Java in order to find the next prime number while the previously returned is false, but I am really confused about how to proceed with "while" code. This is what I have tried until now:
You can create two functions: one (say, isPrime) to check if the number is prime or not and the second (say, nextPrime) to find the next prime. The logic in the second function will be quite straight forward: keep incrementing the number by 1 until isPrime returns true.
Note that you need to check only up to the square root of the number in order to determine if it is prime. Check https://en.wikipedia.org/wiki/Primality_test to learn more about it.
Demo:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
int n = scanner.nextInt();
if (isPrime(n)) {
System.out.println("It is a prime number");
} else {
System.out.println("It is not a prime number. The next prime number is " + nextPrime(n));
}
}
static boolean isPrime(int n) {
if (n == 1 || n == 0) {
return false;
}
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
static int nextPrime(int n) {
while (!isPrime(n)) {
n++;
}
return n;
}
}
A sample run:
Enter an integer: 10
It is not a prime number. The next prime number is 11
Another sample run:
Enter an integer: 11
It is a prime nmber
How about this snippet?
public static void main(String[] args) {
int number= 14; // will print the second SOUT statement with 17
if (isPrime(number)) {
System.out.println(number+ " is a prime number");
} else {
System.out.println(number+ " is not a prime number, " +
"the next prime number is " + nextPrime(number));
}
}
/**
* Check if the number is a prime number
* For 0 or 1 you can return false, for the rest if is divisible by each number
* You might want to throw an exception for the negative input
*/
static boolean isPrime(int number) {
if (number==0 || number==1) {
return false;
}
for (int i=2; i<=number/2; i++) {
if (number%i==0) {
return false;
}
}
return true;
}
/**
* Iterate the number by one until you find a prime number using the while cycle
*/
static int nextPrime(int number) {
int prime;
while (true) {
boolean isPrime = isPrime(++number);
if (isPrime) {
prime = number;
break;
}
}
return prime;
}
In order to find a prime number, you basically need a nested loop. So I'd recomend having your for loop INSIDE the while loop. OR you can have a do-while loop on the outside that keeps looping until you found a prime number.
Your code should look like this:
public class PrimeNumbers {
public static boolean check_prime(int num){
for (int i = 2; i <= num-i ; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args){
int num = 6;
boolean isPrime= true;
if(!check_prime(6)){
int nextPrime = num;
do{
nextPrime++;
if (check_prime(nextPrime)) {
isPrime = true;
break;
}else{
isPrime = false;
}
}while(!isPrime);
}
if (isPrime)
System.out.println("Is a prime number");
else
System.out.println("Is not a prime number" +"the next prime number is" + nextPrime);
}}}
I have been trying to figure out why isn't my code working. If I don't do it through a method and put this code in the main method then it keeps repeating. I want to ask the user for a new number every time. And then see if the number is odd or even. If odd then increase the odd count add all the numbers that the user enters. The user should be asked to enter values until the number 0 is entered.
package Week1;
import java.util.Scanner;
public class Task12 {
public void numbers() {
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
System.out.println("Enter number");
int oddnumbers = 0;
do {
int count = 0;
count = count + i;
System.out.println("The total is:" + count);
if (i % 2 == 0) {
System.out.println("The number is Even");
} else if (i != 9) {
oddnumbers += i;
System.out.println("The number is odd");
System.out.println("the count of odd numbers is :" + oddnumbers);
} else
System.out.println("The number is odd");
System.out.println("the count of odd numbers is :" + oddnumbers);
} while (i != 0);
}
public static void main(String[] args) {
Task12 n = new Task12();
n.numbers();
}
}
You should probably have the reading of a number "i = sc.nextInt();" inside the loop, and the variable count outside, like this:
package Week1;
import java.util.Scanner;
public class Task12 {
public void numbers() {
Scanner sc = new Scanner(System.in);
int oddnumbers = 0;
int count = 0;
int i=0;
do {
System.out.println("Enter number");
i = sc.nextInt();
count = count + i;
System.out.println("The total is:" + count);
if (i % 2 == 0) {
System.out.println("The number is Even");
} else if (i != 9) {
oddnumbers += i;
System.out.println("The number is odd");
System.out.println("the count of odd numbers is :" + oddnumbers);
} else
System.out.println("The number is odd");
System.out.println("the count of odd numbers is :" + oddnumbers);
} while (i != 0);
}
public static void main(String[] args) {
Task12 n = new Task12();
n.numbers();
}
}
This code gives the answer to tour spec/question
Reason for not working: You should take input inside do while loop and then check for odd.
public int numbers() {
Scanner sc = new Scanner(System.in);
int num = 0;
int oddSum = 0;
do {
System.out.println("Enter number");
num = sc.nextInt();
if(num == 0) {
break;
} else if (num % 2 != 0) {
oddSum += num;
}
} while (num != 0);
sc.close();
return oddSum;
}
public static void main(String[] args) {
Test n = new Test();
System.out.println(n.numbers());
}
Hello I am trying to reset a counter in java, as I need to print out both the number of factors of a number and the sum of the factors. When I enter multiple integer values, these counters keep adding up. Is there a way in java to reset the counters after each new integer entered? Here is my code so far.
import java.util.Scanner;
public class FindFactors {
public static void main (String args[]) {
Scanner in = new Scanner(System.in);
int num, factorcounter = 0;
int sumfactors = 0;
System.out.print("Enter a positive integer.");
while(in.hasNextInt()) {
num = in.nextInt();
if(num > 0) {
for(int i = 1; i <= num; i++) {
if(num % i == 0) {
factorcounter++;
System.out.println(i + " is a factor of " + num);
sumfactors = sumfactors + i;
}
}
System.out.println("The number of factors: " + factorcounter);
if (sumfactors / 2 == num) {
System.out.println(num + " is a perfect number!");
}
}
else {
System.out.println("Invalid Input");
}
}
}
}
You have to assign zero to your variables.
Scanner in = new Scanner(System.in);
int num,factorcounter = 0;
int sumfactors = 0;
System.out.print("Enter a positive integer.");
while(in.hasNextInt())
{
num = in.nextInt();
factorcounter = 0;
sumfactors = 0;
if(num > 0)
{
for(int i = 1; i <= num; i++)
{
if(num % i == 0)
{
factorcounter++;
System.out.println(i + " is a factor of " + num);
sumfactors = sumfactors + i;
}
}
System.out.println("The number of factors: " + factorcounter);
if (sumfactors/2 == num)
{
System.out.println(num + " is a perfect number!");
}
}
else
{
System.out.println("Invalid Input");
}
}
I can run this code perfectly, but it's not running as intended. I tried to make a isPrime Method, but I keep getting an error where I get multiple responses instead of the intended single response.
For example, if I put in the number 3, I'll get the response:
[number] isn't prime.
[number] is prime.
If I put the number 100, I'll get the response:
[number] isn't prime.
[number] isn't prime.
[number] isn't prime.
...
[number] is prime.
I'll get the "isn't prime." response 99 times and the 100th response will be "is prime." Every once in a while the response "is prime" will show up.
Could anyone let me know what's messing it up?
import java.util.Scanner;
public class Chapter_8_13 {
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("This program helps determine if a number is prime!");
System.out.println("Enter a number: ");
int num = keyboard.nextInt();
for (int i = 2; i <= num; i++)
{
if (num % i == 0)
{
System.out.println(num + " is prime.");
}
else
{
System.out.println(num + " isn't prime.");
}
}
}
}
You set a flag when num is divisible by any i. Then check the value of flag outside loop to find if its prime or not
flag=0;
for (int i = 2; i < num; i++)
{
if (num % i == 0)
{
flag=1;
break;
}
}
if(flag==1)
System.out.println(num + " is prime.");
else
System.out.println(num + " isn't prime.");
NOTE: You need not loop num times. sqrt(num) is enough.
Actually, your algorithm is wrong. Condition if (num % i == 0) says only that num divides by i (and num is not prime).
It should be:
boolean isPrime = true;
for (int i = 2; i <= Math.sqrt(num); i++)
{
if (num % i == 0)
{
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println("is prime");
} else {
System.out.println("isn't prime");
}
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out
.println("This program helps determine if a number is prime!");
System.out.println("Enter a number: ");
int num = keyboard.nextInt();
boolean isPrime = true;
for (int i = 2; i < num; i++) {
if (num % i == 0) {
isPrime = false;
System.out.println(num + " isn't prime.");
break;
}
}
if (isPrime)
System.out.println(num + " is prime.");
}
}