Correctly Printing For Loops in Java - java

I have been working on this program for a few hours and the code is working correctly but I can't seem to get it to print out correctly, it should just be printing once for each value, such as:
number: 6
dividers: 2 3 6 1
prime: is not prime
Output
Can anyone help? Screenshot is attached. Thanks!
public static void main(String[] args) {
Random randomNums = new Random();
int count;
for (int i = 1; i <= 37; i++) {
count = randomNums.nextInt(100) + 1;
System.out.println("number " + count);
for (int b = 1; b<=count; b++) {
if (count % b == 0) {
System.out.println("dividers " + b);
}
}
for (int a = 2; a< count; a++) {
if (count % a == 0) {
System.out.println("is not prime");
}
if (count % a != 0) {
System.out.println("is prime");
}
}
}
}
}

try to write this code :
public static void main(String[] args) {
Random randomNums = new Random();
int count;
for (int i = 1; i <= 37; i++) {
count = randomNums.nextInt(100) + 1;
System.out.println("number " + count);
String dividers = "";
for (int b = 1; b<=count; b++) {
if (count % b == 0) {
dividers += b.toString() +" ";
}
}
// control the print beside loop
System.out.println("dividers " + dividers);
// add the control for whether prime
bool prime = true;
for (int a = 2; a< count; a++) {
if (count % a == 0) {
System.out.println("prime : is not prime");
// add the control for skip loop
prime = false;
break;
}
}
if(prime){
System.out.println("prime : is prime");
}
}
}
}

based upon your logic, I am guessing that if you decide that a number is not a prime then that is the final result,
so
boolean isPrime = true;
String dividers = "";
for (int a = 2; a< count; a++) {
if (count % a == 0) {
isPrime = false;
dividers += a+" ";
}
}
if (isPrime) {
System.out.println ("is Prime");
} else {
System.out.println ("dividers "+dividers);
System.out.println ("is not Prime");
}

Related

How would I get this for loop to print prime numbers only?

What I need it to do is print all of the prime numbers starting at 1 and ending at the input, if the input is also a prime number. Here's my code now:
static void primeNumbers(int n) {
boolean isPrime;
System.out.println("All the prime numbers up to " + n + " are -->");
for (int prime = 2; prime < n; prime = prime++) {
if (n % prime == 0) {
isPrime = false;
}
if(isPrime == true){
System.out.println(prime);
}
}
}
My teacher said that I need to make a nested for loop, but I just don't know what to put in it. I'm also getting an error saying that my last use of isPrime hasn't been initialized.
You need to actually check for primality, and not just see if the number is a factor of n:
static boolean isPrime(int n) {
if (n < 2) {
return false;
}
if (n % 2 == 0) {
return n == 2;
}
for (int k = 3; k * k <= n; k += 2) {
if (n % k == 0) {
return false;
}
}
return true;
}
static void primeNumber(int n) {
System.out.println("All the prime numbers up to " + n + " are -->");
for (int num = 2; num < n; num ++) {
if (isPrime(num)) {
System.out.println(num);
}
}
}
You will need to do something like this for your program to work.
static void primeNumbers(int n) {
boolean isPrime = true;
System.out.println("All the prime numbers up to " + n + " are -->");
for (int prime = 2; prime < n; prime++) {
if (n % prime == 0) {
isPrime = false;
}else{
isPrime = true;
}
if(isPrime){
System.out.println(prime);
}
}
}
It is necessary to initialize isPrime.
And, Eratosthenes' s sieve is famous algorithm for get prime numbers.
I think the URL below will help you.
https://www.geeksforgeeks.org/java-program-for-sieve-of-eratosthenes/
here is one of the solutions
public static void main(String[] args) {
int n = 23;
boolean[] isPrime = new boolean[n + 1];
for (int i = 1; i <= n; i++) {
isPrime[i] = true;
}
for (int i = 2; i <= n / i; i++) {
if (isPrime[i]) {
for (int j = i; j <= n / i; j++) {
isPrime[i * j] = false;
}
}
}
for (int i = 1; i <= n; i++) {
if (isPrime[i]) {
System.out.println(i);
}
}
}

Can't figure out the error Luhn check

Its supose to tell me if a card is valid or invalid using luhn check
4388576018402626 invalid
4388576018410707 valid
but it keeps telling me that everything is invalid :/
Any tips on what to do, or where to look, would be amazing. I have been stuck for a few hours.
It would also help if people tell me any tips on how to find why a code is not working as intended.
im using eclipse and java
public class Task11 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a credit card number as a long integer: ");
long number = input.nextLong();
if (isValid(number)) {
System.out.println(number + " is valid");
} else {
System.out.println(number + " is invalid");
}
}
public static boolean isValid(long number) {
return (getSize(number) >= 13) && (getSize(number) <= 16)
&& (prefixMatched(number, 4) || prefixMatched(number, 5) || prefixMatched(number, 6) || prefixMatched(number, 37))
&& (sumOfDoubleEvenPlace(number) + sumOfOddPlace(number)) % 10 == 0;
}
public static int sumOfDoubleEvenPlace(long number) {
int result = 0;
long start = 0;
String digits = Long.toString(number);
if ((digits.length() % 2) == 0) {
start = digits.length() - 1;
} else {
start = digits.length() - 2;
}
while (start != 0) {
result += (int) ((((start % 10) * 2) % 10) + (((start % 10) * 2) / 2));
start = start / 100;
}
return result;
}
public static int getDigit(int number) {
return number % 10 + (number / 10);
}
public static int sumOfOddPlace(long number) {
int result = 0;
while (number != 0) {
result += (int) (number % 10);
number = number / 100;
}
return result;
}
public static boolean prefixMatched(long number, int d) {
return getPrefix(number, getSize(d)) == d;
}
public static int getSize(long d) {
int numberOfDigits = 0;
String sizeString = Long.toString(d);
numberOfDigits = sizeString.length();
return numberOfDigits;
}
public static long getPrefix(long number, int k) {
String size = Long.toString(number);
if (size.length() <= k) {
return number;
} else {
return Long.parseLong(size.substring(0, k));
}
}
}
You should modiffy your isValid() method to write down when it doesn't work, like this:
public static boolean isValid(long number) {
System.err.println();
if(getSize(number) < 13){
System.out.println("Err: Number "+number+" is too short");
return false;
} else if (getSize(number) > 16){
public static boolean isValid(long number) {
System.err.println();
if(getSize(number) < 13){
System.out.println("Err: Number "+number+" is too short");
return false;
} else if (getSize(number) > 16){
System.out.println("Err: Number "+number+" is too long");
return false;
} else if (! (prefixMatched(number, 4) || prefixMatched(number, 5) || prefixMatched(number, 6) || prefixMatched(number, 37)) ){
System.out.println("Err: Number "+number+" prefix doesn't match");
return false;
} else if( (sumOfDoubleEvenPlace(number) + sumOfOddPlace(number)) % 10 != 0){
System.out.println("Err: Number "+number+" doesn't have sum of odd and evens % 10. ");
return false;
}
return true;
}
My guess for your problem is on the getPrefix() method, you should add some logs here too.
EDIT: so, got more time to help you (don't know if it's still necessary but anyway). Also, I corrected the method I wrote, there were some errors (like, the opposite of getSize(number) >= 13 is getSize(number) < 13)...
First it will be faster to test with a set of data instead of entering the values each time yourself (add the values you want to check):
public static void main(String[] args) {
long[] luhnCheckSet = {
0, // too short
1111111111111111111L, // too long (19)
222222222222222l // prefix doesn't match
4388576018402626l, // should work ?
};
//System.out.print("Enter a credit card number as a long integer: ");
//long number = input.nextLong();
for(long number : luhnCheckSet){
System.out.println("Checking number: "+number);
if (isValid(number)) {
System.out.println(number + " is valid");
} else {
System.out.println(number + " is invalid");
}
System.out.println("-");
}
}
I don't know the details of this, but I think you should work with String all along, and parse to long only if needed (if number is more than 19 characters, it might not parse it long).
Still, going with longs.
I detailed your getPrefix() with more logs AND put the d in parameter in long (it's good habit to be carefull what primitive types you compare):
public static boolean prefixMatched(long number, long d) {
int prefixSize = getSize(d);
long numberPrefix = getPrefix(number, prefixSize);
System.out.println("Testing prefix of size "+prefixSize+" from number: "+number+". Prefix is: "+numberPrefix+", should be:"+d+", are they equals ? "+(numberPrefix == d));
return numberPrefix == d;
}
Still don't know what's wrong with this code, but it looks like it comes from the last test:
I didn't do it but you should make one method from sumOfDoubleEvenPlace(number) + sumOfOddPlace(number)) % 10 and log both numbers and the sum (like i did in prefixMatched() ). Add logs in both method to be sure it gets the result you want/ works like it should.
Have you used a debugger ? if you can, do it, it can be faster than adding a lot of logs !
Good luck
EDIT:
Here are the working functions and below I provided a shorter, more efficient solution too:
public class CreditCardValidation {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int count = 0;
long array[] = new long [16];
do
{
count = 0;
array = new long [16];
System.out.print("Enter your Credit Card Number : ");
long number = in.nextLong();
for (int i = 0; number != 0; i++) {
array[i] = number % 10;
number = number / 10;
count++;
}
}
while(count < 13);
if ((array[count - 1] == 4) || (array[count - 1] == 5) || (array[count- 1] == 3 && array[count - 2] == 7)){
if (isValid(array) == true) {
System.out.println("\n The Credit Card Number is Valid. ");
} else {
System.out.println("\n The Credit Card Number is Invalid. ");
}
} else{
System.out.println("\n The Credit Card Number is Invalid. ");
}
in.close();
}
public static boolean isValid(long[] array) {
int total = sumOfDoubleEvenPlace(array) + sumOfOddPlace(array);
if ((total % 10 == 0)) {
for (int i=0; i< array.length; i++){
System.out.println(array[i]);}
return true;
} else {
for (int i=0; i< array.length; i++){
System.out.println(array[i]);}
return false;
}
}
public static int getDigit(int number) {
if (number <= 9) {
return number;
} else {
int firstDigit = number % 10;
int secondDigit = (int) (number / 10);
return firstDigit + secondDigit;
}
}
public static int sumOfOddPlace(long[] array) {
int result = 0;
for (int i=0; i< array.length; i++)
{
while (array[i] > 0) {
result += (int) (array[i] % 10);
array[i] = array[i] / 100;
}
}
System.out.println("\n The sum of odd place is " + result);
return result;
}
public static int sumOfDoubleEvenPlace(long[] array) {
int result = 0;
long temp = 0;
for (int i=0; i< array.length; i++){
while (array[i] > 0) {
temp = array[i] % 100;
result += getDigit((int) (temp / 10) * 2);
array[i] = array[i] / 100;
}
}
System.out.println("\n The sum of double even place is " + result);
return result;
}
}
I also found a solution with less lines of logic. I know you're probably searching for an OO approach with functions, building from this could be of some help.
Similar question regarding error in Luhn algorithm logic:
Check Credit Card Validity using Luhn Algorithm
Link to shorter solution:
https://code.google.com/p/gnuc-credit-card-checker/source/browse/trunk/CCCheckerPro/src/com/gnuc/java/ccc/Luhn.java
And here I tested the solution with real CC numbers:
public class CreditCardValidation{
public static boolean Check(String ccNumber)
{
int sum = 0;
boolean alternate = false;
for (int i = ccNumber.length() - 1; i >= 0; i--)
{
int n = Integer.parseInt(ccNumber.substring(i, i + 1));
if (alternate)
{
n *= 2;
if (n > 9)
{
n = (n % 10) + 1;
}
}
sum += n;
alternate = !alternate;
}
return (sum % 10 == 0);
}
public static void main(String[] args){
//String num = "REPLACE WITH VALID NUMBER"; //Valid
String num = REPLACE WITH INVALID NUMBER; //Invalid
num = num.trim();
if(Check(num)){
System.out.println("Valid");
}
else
System.out.println("Invalid");
//Check();
}
}

How to make a newline for every 15 spaces with numbers in java

I have the following code that finds the prime factors from 1 to the user input. The problem is that the output is in one very long line, I want every 15 numbers to output then go to the next line. How would I do that?
Here is my code:
public static void main (String args[])
{
System.out.println("\nLab1la\n");
Scanner input = new Scanner(System.in);
System.out.println("Enter the primes upperbond ==>> ");
final int MAX = input.nextInt();
input.nextLine();
boolean primes[];
primes = new boolean[MAX];
ArrayList<Integer>PrimeFactor = new ArrayList<Integer>();
for (int i = 2; i < MAX + 1 ; i++)
{
PrimeFactor.add(i);
}
System.out.println("COMPUTING RIME NUMBERS");
System.out.println();
System.out.println("PRIMES BETWEEN 1 AND " + MAX);
CompositeNumbers(PrimeFactor);
for (int value : PrimeFactor)
{
System.out.print(value);
System.out.print(" ");
}
}
public static void CompositeNumbers(ArrayList<Integer> PrimeFactor)
{
for (int i = 0; i < PrimeFactor.size(); i++)
{
if (!isPrime(PrimeFactor.get(i)))
{
PrimeFactor.remove(i);
i--;
}
}
}
public static boolean isPrime(int n)
{
if(n==1)
{
return true;
}
for (int i = 2; i < n +1/2; i++)
{
if (n%i == 0)
{
return false;
}
}
return true;
}
}
You could do something like this:
for (int i = 0; i < PrimeFactor.size(); i++)
{
if (i > 0 && i % 15 == 0) System.out.println();
System.out.print(PrimeFactor.get(i));
System.out.print(" ");
}
You could just have a counter and take a mod of this counter value for 15 and print it in the next line, like below. Like #soong described
int counter = 0;
for (int value : PrimeFactor)
{
if(counter % 15 == 0){
System.out.println();
}
System.out.print(value);
System.out.print(" ");
counter++;
}

Why is my method repeating when I run

public class PalindromicPrimes {
public static void main (String[] args) {
userInt();
System.out.println("The palindromic primes less than " + userInt() +
" are:");
for (int i = 0; i <= userInt(); i++) {
if (isPrime() && isPalindrome()) {
System.out.println(i);
}
}
}
private static boolean isPrime() {
if (userInt() == 2 || userInt() == 3) {
return true;
}
if (userInt() % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(userInt()) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (userInt() % i == 0) {
return false;
}
}
return true;
}
private static boolean isPalindrome() {
if (userInt() < 0)
return false;
int div = 1;
while (userInt() / div >= 10) {
div *= 10;
}
while (userInt() != 0) {
int x = userInt();
int l = x / div;
int r = x % 10;
if (l != r)
return false;
x = (x % div) / 10;
div /= 100;
}
return true;
}
private static int userInt() {
Scanner s = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int userInt = s.nextInt();
return userInt;
}
}
is there a different way of getting the user input? or can I keep it this way?
when it runs it just keeps prompting the user input.
rearrange it like this:
public static void main (String[] args) {
//get it and save it here!
int userValue = userInt();
System.out.println("The palindromic primes less than " + userValue +
" are:");
for (int i = 0; i <= userValue; i++) {
if (isPrime(userValue) && isPalindrome(userValue)) {
System.out.println(i);
}
}
}
then also update all the methods that care about this "userInt" value.
Every time you call userInt() you're telling the code to get a new value from the command line.
Try this:
public static void main (String[] args) {
int value = userInt();
System.out.println("The palindromic primes less than " + value +
" are:");
for (int i = 0; i <= value; i++) {
if (isPrime() && isPalindrome()) {
System.out.println(i);
}
}
}
The term userInt() is a function invocation that prompts the user for input. Odds are you only want to do this once. You're doing it multiple times.
You should store the result of userInt() in a variable.
int typed = userInt();
And then use this variable to reference what the user typed instead of calling userInt() again.
System.out.println("The palindromic primes less than " + typed +
" are:");
for(int i = 0; i < typed; i++) ...
You keep calling userInt(). That is the problem.
I don't understand your logic. So I have not modified that code. But the code runs.
import java.util.Scanner;
public class PalindromicPrimes {
public static void main (String[] args) {
int x = userInt();
System.out.println("The palindromic primes less than " + x +
" are:");
for (int i = 0; i <= x; i++) {
if (isPrime(i) && isPalindrome(i)) {
System.out.println(i);
}
}
}
private static boolean isPrime(int a) {
if (a == 2 || a == 3) {
return true;
}
if (a % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(a) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (a % i == 0) {
return false;
}
}
return true;
}
private static boolean isPalindrome(int a) {
if (a < 0)
return false;
int div = 1;
while (a / div >= 10) {
div *= 10;
}
while (a != 0) {
int x = a;
int l = x / div;
int r = x % 10;
if (l != r)
return false;
x = (x % div) / 10;
div /= 100;
}
return true;
}
private static int userInt() {
Scanner s = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int userInteger = s.nextInt();
return userInteger;
}
}
Remember, don't use the same names for variable and function. In the function userInt(), you have used a variable int userInt, to get the result from the scanner. This might be aa recursive call sometimes. Be careful with that.

Consecutive factor test

A positive number n is consecutive-factored if and only if it has factors, i and j where i > 1, j > 1 and j = i +1. I need a function that returns 1 if its argument is consecutive-factored, otherwise it returns 0.For example, 24=2*3*4 and 3 = 2+1 so it has the function has to return 1 in this case.
I have tried this:
public class ConsecutiveFactor {
public static void main(String[] args) {
// TODO code application logic here
Scanner myscan = new Scanner(System.in);
System.out.print("Please enter a number: ");
int num = myscan.nextInt();
int res = isConsecutiveFactored(num);
System.out.println("Result: " + res);
}
static int isConsecutiveFactored(int number) {
ArrayList al = new ArrayList();
for (int i = 2; i <= number; i++) {
int j = 0;
int temp;
temp = number %i;
if (temp != 0) {
continue;
}
else {
al.add(i);
number = number / i;
j++;
}
}
System.out.println("Factors are: " + al);
int LengthOfList = al.size();
if (LengthOfList >= 2) {
int a =al(0);
int b = al(1);
if ((a + 1) == b) {
return 1;
} else {
return 0;
}
} else {
return 0;
}
}
}
Can anyone help me with this problem?
First check if its even, then try trial division
if(n%2!=0) return 0;
for(i=2;i<sqrt(n);++i) {
int div=i*(i+1);
if( n % div ==0) { return 1; }
}
return 0;
very inefficient, but fine for small numbers. Beyond that try a factorisation algorithm from http://en.wikipedia.org/wiki/Prime_factorization.
I have solved my problem with the above code. Following is the code.
public class ConsecutiveFactor {
public static void main(String[] args) {
// TODO code application logic here
Scanner myscan = new Scanner(System.in);
System.out.print("Please enter a number: ");
int num = myscan.nextInt();
int res = isConsecutiveFactored(num);
System.out.println("Result: " + res);
}
static int isConsecutiveFactored(int number) {
ArrayList al = new ArrayList();
for (int i = 2; i <= number; i++) {
int j = 0;
int temp;
temp = number % i;
if (temp != 0) {
continue;
}
else {
al.add(i);
number = number / i;
j++;
}
}
Object ia[] = al.toArray();
System.out.println("Factors are: " + al);
int LengthOfList = al.size();
if (LengthOfList >= 2) {
int a = ((Integer) ia[0]).intValue();
int b = ((Integer) ia[1]).intValue();
if ((a + 1) == b) {
return 1;
} else {
return 0;
}
} else {
return 0;
}
}
}

Categories