Why does the int j only get the value 2? Doesn't (int)realNum mean that it must be a natural number?
Scanner basicNum = new Scanner(System. in );
String insertNum = JOptionPane.showInputDialog(null, "Insert a number\n");
int realNum = Integer.parseInt(insertNum);
int j = realNum = 1;
if (realNum < 10000) {
while ((realNum / j == (int) realNum)) {
j++;
}
System.out.println(j);
if (j > 2) {
JOptionPane.showMessageDialog(null, "It is not a prime!!");
}
if (j < 2) {
JOptionPane.showMessageDialog(null, "It is a prime!");
}
} else {
JOptionPane.showMessageDialog(null, "Too large number!");
}
In Java 8, you can easily do it like this:
boolean isPrime(final int n) {
return IntStream.range(2, n / 2+1).noneMatch(i -> n % i == 0);
}
On earlier versions, this one should do the same work,
String insertNum = JOptionPane.showInputDialog(null, "Insert a number\n");
int realNum = Integer.parseInt(insertNum);
boolean prime = true;
for (int i = 2; i <= realNum / 2; i++) {
if (realNum % i == 0) {
JOptionPane.showMessageDialog(null, "It is not a prime!!");
prime = false;
break;
}
}
if (prime) {
JOptionPane.showMessageDialog(null, "It is a prime!");
}
int j = realNum = 1; sets j and realNum to 1.
So realNum / j == (int)realNum is true until j is greater than 1. Hence your output.
The (int) prefix on (int)realNum is superfluous since realNum is already an int type.
Also realNum / j will be evaluated in integer arithmetic: any remainder is truncated.
Related
I am trying to implement a code to check whether a given array of numbers is prime or not,
but when the number is not a prime number, the output displays "Prime" and "Not Prime" both answers. What is the mistake I did here and it is a pleasure to have an answer from you? Thank you in advance!
Here is my code.
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
int[] arr = new int[number];
for (int i = 0; i < number; i++) {
arr[i] = scan.nextInt();
}
for (int i = 0; i < number; i++) {
int num = arr[i];
for (int j = 2; j <= Math.sqrt(num); j++) {
if (num % j == 0 && num !=2) {
System.out.println(num + "Not prime");
break;
}
}
System.out.println(num +"Prime");
}
If you're interested in making your code a little more efficient you can go this route.
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20 };
for (int num : numbers) {
System.out.println(num + ((isPrime(num) ? " is" : " is not") + " a prime"));
}
private static boolean isPrime(int num) {
// two is a prime
if (num == 2) {
return true;
}
// numbers 1 or less or any even
// number (sans 2) are not primes
if (num <= 1 || num % 2 == 0) {
return false;
}
// Now you can check for odd divisors.
// and increment by 2 starting with 3.
for (int i = 3; i <= Math.sqrt(num); i+=2) {
if (num % i == 0) {
return false;
}
}
return true;
}
You should remember whether the number was prime or not. Your code doesn't do that so both prints are reached.
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
int[] arr = new int[number];
for (int i = 0; i < number; i++) {
arr[i] = scan.nextInt();
}
for (int i = 0; i < number; i++) {
int num = arr[i];
boolean isPrime = true;
for (int j = 2; j <= Math.sqrt(num); j++) {
if (num % j == 0 && num !=2) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println(num +"Prime");
} else {
System.out.println(num + "Not prime");
}
}
Use a boolean to track whether the number is prime. Assume it's true (prime) to begin with and set it false if it is discovered not to be prime.
boolean isPrime = true;
Afterwards, determine the message based on that boolean.
String message = isPrime ? "Prime" : "Not prime";
You can fix it for example by introducing a boolean variable:
for (int i = 0; i < number; i++) {
int num = arr[i];
boolean isPrime = true;
for (int j = 2; j <= Math.sqrt(num); j++) {
if (num % j == 0 && num !=2) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println(num +"Prime");
} else {
System.out.println(num + "Not prime");
}
}
I wanted to use a for and a while loop to obtain the prime factors of a number. My while loop example works fine which I have posted below my for loop example. However, my for loop does not work, and i am guessing that I can't use a continue in the same manner that I used it in the while loop. If this is true, then how would I accomplish this. I have not been able to find a basic beginners example of this using a for loop. Thanks
// My getting largest prime factor using a for loop
public class LargestPrime{
public static void main(String[] args) {
int number = 36;
int largestPrime = 0;
for ( int i = 2; i <= number; i++){
if (number % i == 0){
largestPrime = i;
number /= i;
continue;
}
System.out.println(" largest prime = " + i);
}
}
}
//*******************************************************************
//*******************************************************************
public class LargestPrime {
// gettting largest prime using a while loop
public static int getLargestPrime(int number) {
if (number <= 1) {
return -1;
}
int largestPrime = 0;
int count = 2;
while (count <= number) {
if (number % count == 0) {
largestPrime = count;
number = number / count;
continue;
}
count++;
}
return largestPrime;
}
}
The problem is that continue in a for loop executes the update part (i++), which your while loop didn't.
The other problem is that you're printing inside the loop.
There are multiple way to fix this:
Do i-- before continue, so it evens out to nothing with the i++. This is a fairly common way to handle this.
Since you don't have any code after the if statement, you don't need the continue.
for (int i = 2; i <= number; i++) {
if (number % i == 0) {
largestPrime = i;
number /= i;
i--; // to retry same `i` value
}
}
Do the i++ "yourself", i.e. not as part of for loop:
for (int i = 2; i <= number; ) {
if (number % i == 0) {
largestPrime = i;
number /= i;
continue;
}
i++;
}
Or:
for (int i = 2; i <= number; ) {
if (number % i == 0) {
largestPrime = i;
number /= i;
} else {
i++;
}
}
Use a while loop inside the for loop:
for (int i = 2; i <= number; i++) {
while (number % i == 0) {
largestPrime = i;
number /= i;
}
}
That can be shortened to:
for (int i = 2; i <= number; i++)
for (; number % i == 0; number /= i)
largestPrime = i;
Though rather than assign largestPrime repeatedly, you could do this:
for (int i = 2; i <= number; i++) {
if (number % i == 0) {
largestPrime = i;
do {
number /= i;
} while (number % i == 0);
}
}
Hey so im trying to create a program that prints out the first 100 prime numbers. this is my code however it doesn't print out the first hundred but the primes from 2 to 100. what am i doing wrong here that make it print out only those ant not the first hundred?
import java.io.*;
import java.util.*;
import java.lang.*;
import java.text.*;
public class Prime {
public static void main(String[] args) {
int maxCount = 100;
int[] values = new int[maxCount];
int temp = 3;
boolean prime = true;
for (int j = 1; j < maxCount; ++j) {
values[j] = j + 1;
if (values[j] == 2) {
System.out.println(values[j]);
}
}
for (int j = 2; j < maxCount; ++j) {
if (values[j] % 2 == 0)
prime = false;
else {
boolean prime2 = true;
double test = Math.sqrt(values[j]);
int divisor = 3;
while (prime2 && (divisor <= test)) {
if (values[j] % divisor == 0) {
prime2 = false;
} else divisor += 2;
}
if (prime2)
System.out.println(values[j]);
}
}
}
}
You're looping until j < maxCount while you should loop until the number of elements in the array are equal to maxCount. For that you'll need another counter which is val_cnt in the following fixed code.
import java.io.*;
import java.util.*;
import java.lang.*;
import java.text.*;
public class Prime {
public static void main(String[] args) {
int maxCount = 100;
int[] values = new int[maxCount];
int temp = 3;
int val_cnt = 0;
values[val_cnt++] = 2;
System.out.println(2);
for (int j = 3; val_cnt < maxCount; ++j) {
boolean prime = true;
if (j % 2 == 0)
prime = false;
else {
double test = Math.sqrt(j);
int divisor = 3;
while (prime && (divisor <= test)) {
if (j % divisor == 0) {
prime = false;
} else divisor += 2;
}
if (prime) {
values[val_cnt++] = j;
System.out.println(j);
}
}
}
}
}
you are making your loop iterate till j becomes 100 , and at every iteration irrespective of whether a prime number has been found or not, j gets incremented.
So have something like:-
while(maxCount<100){
if(number_is_prime){
increment maxCount;
}
else{
continue;
}
You are iterating your loop till 100 only. But you want to print first 100 prime numbers, not prime numbers between 1 to 100. so every time the number is found to be a prime number just increment the count(which counts the number of prime numbers printed.) to 1 and exit from the loops when the count is 100.Here is the simple approach for printing first 100 prime numbers:
int count = 0,flag=0;
for(int i=2;count<100;i++){
flag = 0;
for(int j=2;j<i;j++){
if(i%j == 0){
flag ++;
break;
}
}
if(flag == 0){
System.out.println(i);
count++;
}
}
Only increase the value of j if prime number is found,
Re-format your codes same as this,
for (int j = 2; j < maxCount;) {
if (values[j] % 2 == 0){
prime = false;
j++;
}
else {
boolean prime2 = true;
double test = Math.sqrt(values[j]);
int divisor = 3;
while (prime2 && (divisor <= test)) {
if (values[j] % divisor == 0) {
prime2 = false;
} else divisor += 2;
}
if (prime2)
System.out.println(values[j]);
j++;
}
Try this
class PrimeNumbers {
public static void main (String[] args) {
int i =0; int num =0;
String primeNumbers = "";
for (i = 1; i <= 100; i++) {
int counter=0;
for(num =i; num>=1; num--) {
if(i%num==0) {
counter = counter + 1;
}
}
if (counter ==2) {
primeNumbers = primeNumbers + i + " ";
}
}
System.out.println("Prime numbers from 1 to 100 are :");
System.out.println(primeNumbers);
}
}
For those who are familiar with Luhn's Algorithm, I am compiling a program that verify credit card numbers using this Algorithm. Here's what I have already:
Scanner input = new Scanner(System.in);
String ccNum = "";
int product = 0;
int sum = 0;
System.out.print("Please enter a credit card #: ");
ccNum = input.next();
for(int i = 0 + 1; i < ccNum.length(); i--){
int number = Integer.parseInt(ccNum.substring(i, i + 1));
if(i % 2 != 0){
product = number * 1;
}
else{
product = number * 2;
}
if(product > 9){
product -= 9;
sum += product;
}
}
boolean valid = (sum % 10 == 0);
if(valid){
System.out.println("Valid!");
}
else{
System.out.println("Invalid!");
}
}
}
I am confused about this program. When I run it, I got the "StringIndexOutOfBoundsExpection" error. What should I change up? We cannot use arrays with this program, however. Instead of the full 16-digit number, we are only using 8 digits.
Try this.
boolean alt = false;
for(int i = ccNum.length() - 1; i >= 0; i--, alt = !alt){
int number = ccNum.charAt(i) - '0';
if(alt)
number *= 2;
if(number > 9)
number -= 9;
sum += number;
}
boolean valid = (sum % 10 == 0);
I am supposed to create a perfect number class using the following pseudocode:
For i from 2 to “very large”,
For j from 2 to √i,
if (j evenly divides i),
accumulate the sum j and i/j
if √i is an integer
subtract √i ... you added it twice
if the sum of divisors == i
Print the number ... it’s perfect!
So here is my version. It runs, but it doesn't do what I want at all. It just runs and produces nothing as an output. Can someone tell me what is wrong with my program? It's bothering me so much.
import java.util.Scanner;
public class PerfectNumber {
public static void main(String[] args) {
double sum = 0
double newsum = 0;
for (int i = 2; i < 1000000; i++) {
for (int j = 2; i<Math.sqrt(i); j++){
if (i%j==0){
sum = j + (i%j);
}
if (Math.sqrt(i)==(int)i){
newsum = sum - Math.sqrt(i);
}
if (sum == 0) {
System.out.println(sum + "is a perfect number");
}
}
}
}
}
Few mistakes according to the algorithm:
sum = j + (i%j); should be changed to sum = j + (i/j);
This piece:
if (Math.sqrt(i)==(int)i){
newsum = sum - Math.sqrt(i);
}
if (sum == 0) {
System.out.println(sum + "is a prime number");
}
Should be under upper "for"
Math.sqrt(i)==(int)i would never be true unless i is 1. If you want to check this that way you should write Math.sqrt(i)==((int) Math.sqrt(i))
There are much more errors, the simplest way to do it is:
double sum = 0;
for (int i = 1; i <= 10000; i++) {
for (int j = 1; j < i; j++) {
if (i % j == 0) {
sum += j;
}
}
if (i == sum) {
System.out.println(sum + " is a prime number");
}
sum = 0;
}
Your code contains several mistakes. Here is the corrected code, commented with the changes.
// newsum isn't needed; declare sum to be int to avoid floating-point errors
int sum = 0;
for (int i = 2; i < 1000000; i++) {
// Start with 1; every natural number has 1 as a factor.
sum = 1;
// Test if j, not i, is less than the square root of i.
for (int j = 2; j <= Math.sqrt(i); j++){
if (i % j == 0){
// Add to sum; don't replace sum. Use i / j instead of i % j.
sum = sum + j + (i / j);
// Move test inside this if; test if j is square root of i
if (j*j == i){
// I used j because we know it's the square root already.
sum = sum - j;
}
}
// Move print outside of inner for loop to prevent multiple
// printings of a number.
// Test if sum equals the number being tested, not 0.
if (sum == i) {
// Space before is
System.out.println(sum + " is a perfect number");
}
}
}
Output:
6 is a perfect number
28 is a perfect number
496 is a perfect number
8128 is a perfect number
public static void main(String[] args){
int min = 2;
int max = 1000000;
int sum = 0;
for (; min <= max; min++,sum = 0) {
for (int e = 1; e < min; e++)
sum += ((min % e) == 0) ? e : 0;
if (sum == min){
System.out.println(sum);
}
}
}
for(n=1;n<=number;n++){ //calculates the sum of the number.
int i=1;
int sum = 0;
while(i<n){
if(n%i==0)
sum+=i;
i++;
}
if(sum==n){ //if the sum is equal to its sum :
System.out.print(n+": ");
for (int j = 1;j<n;j++){
if(n%j==0){
System.out.print(j+" ");
}
}
System.out.println();
}
}
Here is the simplest and easiest form you can write a program for perfect number....this code gives perfect number within 25 ...you can change as you want
import java.util.Scanner;
public class PerfectNumber {
public static void main(String[] args) {
int n,i,j,count=0;
for(i=2;i<=25;i++) {
for(j=1;j<=i;j++) {
if(i%j ==0) /*count increments if a reminder zero*/ {
count++;
}
}
/*since a perfect number is divided only by 1 and itself
if the count is 2 then its a prime number...*/
if(count==2)
System.out.println(i);
count=0;
}
return 0;
}
}
According to the pseudocode you want to move the second and third if test outside of the inner loop
for (int i = 2; i < 1000000; i++) {
double iroot = Math.sqrt(i);
int sum = 1;
for (int j = 2; j <= iroot; j++){
if (i % j == 0){
sum = sum + j + i / j;
}
}
if (iroot == (int) iroot) {
sum = sum - iroot;
}
if (sum == i) {
System.out.println(sum + "is a perfect number");
}
}
Thanks for watched
public boolean testPerfect(int n){
int i=1;
int sum=0;
while(i<n){
if(n%i==0)
{
sum+=i++;
}
else{
i++;}
}
if (sum==n){
return true;
}
return false;
}