I've looked at a few different stack questions and googled, but nothing I've read really has dealt with reversal of integers, but just strings.
So right now my code may or may not work at all, and it may be the dumbest thing you've ever seen, and that's okay and corrections are welcomed, but from what I hope my code will be doing is going through 100 - 999 multiplying the two ints and then checking whether it's palindromic or not. The if with reverse.equals(sum) is totally pseudocode and obviously won't work, however I can't figure out how to do a check for a palindromic int. Is there a simple way to do this? I've read some pretty lengthy and complicated ways, but I'm sure there's gotta be a simple way. Maybe not. :/. Anyway, here's my code.
public class PalandromicNum {
public static void main(String[] args){
int numOne = 100;
int numTwo = 100;
int toteVal;
int counter = 1000;
int sum = 0;
int finalSum = 0;
for(int i=0; i<counter; i++){
toteVal = numOne * numTwo;
numTwo++;
if(numTwo == 999){
numOne++;
numTwo = 100;
}
if(toteVal < sum){
sum += toteVal;
if(reverse.equals(sum)){
finalSum = sum;
System.out.println(finalSum);
}
}
}
}
}
Thanks again in advance!
This is on my phone so sorry for any errors.
Convert your number to a String and:
public static boolean isPalindrome(String str)
{
// base recursive case
if (str.length <= 1) {
return true;
}
// test the first and last characters
char firstChar = str.charAt(0);
char lastChar = str.charAt(str.length - 1) // subtract 1 as indexes are 0 based
if (!firstChar.equals(lastChar)) {
return false;
}
// if the string is longer than 2 chars and both are equal then recursively call with a shorter version
// start at 2nd char, end at char before last
return isPalindrome(str.substring(1,str.length);
}
Reversing integers is quite easy. Remember mod 10 gives u last digit. Loop over it, chopping off last digit of the number one at a time and adding it to reverse to new number. Then its matter of simple integer equality
int rev = 0;
int n = sum;
while(n)
{
rev = rev*10 + n%10;
n /= 10;
}
if(sum==rev)
//palindrome
else
//no no no no.
You can create a function named isPalindrome to check whether a number is a palindrome.
Use this function in your code.
You just need to pass the number you want to check into this function.
If the result is true, then the number is a palindrome.
Else, it is not a palindrome.
public static boolean isPalindrome(int number) {
int palindrome = number; // copied number into variable
int reverse = 0;
while (palindrome != 0) {
int remainder = palindrome % 10;
reverse = reverse * 10 + remainder;
palindrome = palindrome / 10;
}
// if original and reverse of number is equal means
// number is palindrome in Java
if (number == reverse) {
return true;
}
return false;
}
}
I believe that this code should help you out if you are trying to find out how many palindromes are between 100-999. Of course, it will count palindromes twice since it looks at both permutations of the palindromes. If I were you I would start creating methods to complete a majority of your work as it makes debugging much easier.
int total = 100;
StringBuilder stringSumForward;
StringBuilder stringSumBackward;
int numberOfPals = 0;
for(int i = 100; i < 999; i++){
for(int j = 100; j < 999; j++){
total = i * j;
stringSumForward = new StringBuilder(String.valueOf(total));
stringSumBackward = new StringBuilder(String.valueOf(total)).reverse();
if(stringSumForward.toString().equals(stringSumBackward.toString())){
numberOfPals++;
}
}
}
Related
So I was trying to make a prime number calculator in java that goes from 1 up to the upper limit of the range given by the user and prints out all of the primes.
One way of approaching this was by simply using a nested for loop and testing divisibility for every number in the range by all of the numbers less than it.
However, I figured it would be more efficient to only test prime numbers to avoid repeated factors and speed up the program.
For example, if the number we were on was 16, rather than testing if it's divisible by 2,3,4,5,...14,15,16, I could only test out 2,3,5,7,11,13 and stop once a factor is found.
So I tried to make an array to store all of the primes found so far and only use those values to test for the next number.
Here's my code, I can't figure out why it's not working
Scanner sc = new Scanner (System.in);
System.out.print ("Enter the upper limit: ");
int high = sc.nextInt();
boolean isPrime = true;
int[] primearray = new int[0];
for (int num = 1; num <= high; num++)
{
for (int x: primearray)
{
if (num%x==0)
{
isPrime = false;
break;
}
}
if (isPrime == true) {
int size = primearray.length;
primearray = new int[size+1];
primearray [size] = num;
System.out.println (num);
}
}
First of all, 1 isn't prime. By starting your outer loop at 1, your prime array ends up with 1 in it and everything else will then test as not prime. Start your outer loop at int num = 2.
Second, you aren't copying over the existing known primes when you expand primearray. You can use
primearray = Arrays.copyOf(primearray, size+1);
which will make a new array with all the old contents copied and space for one more value.
Finally, you might want to check out the Sieve of Eratosthenes. A careful implementation of that algorithm will be more efficient than your current algorithm, which requires an expensive array reallocation every time you find a prime. You can use a BitSet to keep track of the flags that the sieve needs.
You have wrong in logic
boolean isPrime = true;
this variable should be declared in for loop, let 's imagine, if you find out 4 is not prime then isPrime = false, then you check 5 but there is not any code block that set isPrime = true.
And this block:
if (isPrime == true) {
int size = primearray.length;
primearray = new int[size+1];
primearray [size] = num;
System.out.println (num);
}
You created new array of prime number, primearray with size increased by 1, so primearray does not contain any old prime number, that will make wrong while checking prime. So you need to copy old prime numbers to new array.
And because the prime numbers start by 2, so your code should be:
Scanner sc = new Scanner(System.in);
System.out.print("Enter the upper limit: ");
int high = sc.nextInt();
int[] primeArray = new int[0];
for (int num = 2; num <= high; num++)
{
boolean isPrime = true;
for (int x : primeArray)
{
if (num % x == 0)
{
isPrime = false;
break;
}
}
if (isPrime == true)
{
primeArray = Arrays.copyOf(primeArray, primeArray.length + 1);
primeArray[primeArray.length - 1] = num;
System.out.println(num);
}
}
You should use a Sieve of Eratosthenes to find primes, rather than testing each number for divisibility; that method is far slower than sieving. Here is an implementation of sieving from my blog:
public static LinkedList sieve(int n)
{
BitSet b = new BitSet(n);
LinkedList ps = new LinkedList();
b.set(0,n);
for (int p=2; p<n; p++)
{
if (b.get(p))
{
ps.add(p);
for (int i=p+p; i<n; i+=p)
{
b.clear(i);
}
}
}
return ps;
}
As you say the key simplification is to only test primes when you find the next prime. For example:
public class PrimeGenerator {
private long current = 1;
private final List<Long> primes = new ArrayList<>();
public long next() {
do {
current++;
} while (primes.stream().anyMatch(n -> current % n == 0));
primes.add(current);
return current;
}
public LongStream stream() {
return LongStream.generate(this::next);
}
}
This records each prime as it is generated.
You can generate get all primes to a certain value with
generator.stream().takeWhile(p -> p < value)...
Previous answers already explains what is wrong with your code.
I just want to share another approach which is more efficient. The sample implementation is as per below. Basically, once we know x is prime number, we also know i*x is NOT a prime number. Further reading and visualization is available here
public int countPrimes(int n) {
if (n == 0 || n == 1) return 0;
int count = 0;
boolean[] check = new boolean[n+1];
for (int i = 2; i < n; i++) {
if (check[i]) continue;
for (int j = 1; j <= n / i; j++) {
check[j * i] = true;
}
count++;
}
return count;
}
I've recently taken up a computer organization course in where we learn binary hex etc, I took it upon myself to attempt to create a program that will count from 0 up to an input number, however the counting is done in binary. I've run into some trouble and confused myself beyond belief, some clarification and assistance would be greatly appreciated. Specifically speaking, how can I efficiently and effectively replace the values of a string containing the previous binary number, with 0's and 1's using some sort of for-loop. I'm aware that there is some method for directly converting a string to binary, however; I wanted to do this more complicated method for practice.
package counting;
import java.util.Scanner;
public class counting
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Hello, this is a number counter, please enter the integer you would like to count to");
int number = input.nextInt();
String start = "0000000000";
// 000~etc is used as the start simply because i'm not sure how to calculate how many digit places
//the number input by the user will have
StringBuilder cont = new StringBuilder(start);
System.out.println(start);
/*What i intend to do is have the binary loop counter continue until it reaches
* the number input by the user, afterwards, working in a right to left manner, start counting from
* 0 up to the number given by the user, starting with 0. then using another loop, still using
* the right to left manner, if there is a 0, it should be replaced with a 1, and if there is a
* 1, it should be replaced with a 0, and the character before it should be replaced with a 1, if there
* is no room, continue to the left until there is a space available for a 1 and then reset all values
* after the 1 back to zero, and resume counting. the way i see it is requires a for loop to be used
* as the current position of a cursor used to determine what changes must be made
*/
for(int i = 0; i < number; i++)
{
int l = start.length();
for(int n = 0; n <= number; n++)
{
for(int w = 1; w <= l; w++)
{
if (cont.charAt(l-w) == '0')
{
cont.setCharAt((cont.length()-w), '1');
System.out.println(cont);
}
else if (cont.charAt(l-w) == '1')
{
cont.setCharAt((cont.length()-w), '0');
cont.setCharAt((cont.length()-(w+1)), '1');
System.out.println(cont);
}
}
}
System.out.println(cont);
}
}
}
Here is a little loop that will do what you are looking for. You just have to remember powers of 2 to count in binary.
public static char flip(char c){
if(c == '0')
return '1';
else
return '0';
}
public static void main(String[] args) {
String start = "0000000000";
StringBuilder cont = new StringBuilder(start);
int number = (int)Math.pow(2,10);
for(int i = 0; i < number; i++)
{
if(i != 0){
int val = (int)Math.floor(i/2);
for(int j = 0; j <= val; j++){
// Flip any bit that when modded by 2^j == 0
if(i % Math.pow(2,j) == 0){
cont.setCharAt((cont.length() - (j + 1)), flip(cont.charAt(cont.length() - (j + 1))));
}
}
}
System.out.println(cont);
}
}
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++;
}
I'm trying to find prime numbers with a specific condition in Java.
The challenge is to show all the prime numbers (under 100.000) which contain a '3' four times.
I already have a code which shows all the prime numbers under 100.000, but I can't seem to figure out how to count the ones that contain the number '3' four times.
I can however count all the prime numbers.
Can someone help me with this?
Here's the code I have, where am I going to put the numbers into strings?
package Proeftentamen;
import java.util.regex.*;
/**
*
* #author Stefan
*/
public class Vraag_6 {
/// priemgetallen waar 4x een 3 in voor komt???? wtf...
public static void main(String[] args) {
boolean[] lijst = new boolean[1000000]; // hoeveelheid getallen
vularray(lijst);
lijst = zeef(lijst);
drukaf(lijst);
}
public static void vularray(boolean[] lijst) {
for (int i = 2; i < lijst.length; i++) {
lijst[i] = true;
}
}
public static boolean[] zeef(boolean[] lijst) {
for (int i = 2; i < lijst.length / 2; i++) {
if (lijst[i]) {
for (int j = 2 * i; j < lijst.length; j += i) {
lijst[j] = false;
}
}
}
return lijst;
}
public static void drukaf(boolean[] lijst) {
int count = 0;
for (int i = 2; i < lijst.length; i++) {
if (lijst[i] == true) {
System.out.println(i + " " + lijst[i]);
count++;
}
}
System.out.println("Aantal priemgetallen: " + count);
}
}
This question really sounds like a homework, so you should write down what you have come up with and what you tried so far.
There are a lot of ways to count numbers. Just to give you a clue, you can use the reminder operation (in Java - %):
56 % 10 = 6
25 % 5 = 0
So, when you divide by 10 and use a reminder operation you can get the last digit of your number. Now use a loop and counter and you'll be fine.
Another option (very ugly, so don't really use it :) ) - to turn your number into a String and iterate (loop) over its characters.
Hope this helps and good luck!
This code generate 50 permutation of numbers that has four '3' in it's digits
so check each number that is prime or not
public void generateNumbers() {
StringBuilder s = new StringBuilder();
s.append("3333");
for (int i = 0; i < 5; i++) {
for (int j = 0; j <= 9; j++) {
if (j%3==0) continue;
s.insert(i,String.valueOf(j));
int number=Integer.parseInt(s.toString());
System.out.println(number);
s.delete(i,i+1);
}
}
}
Iterate across each prime number.
For each prime number, convert it to a string using the Integer.toString(int) static method.
With this string, iterate over every character (use a for loop and the non-static method String.charAt(int index)) and count the number of times that method returns '3'. (The character '3', not the String "3").
Unless you have some other purpose for an array of prime-number Strings, don't bother to store them anywhere outside the loop.
Please refer below code to validate all such prime numbers.
void getPrimes(int num ,int frequency,char digit) {
int count = 0;
String number=Integer.toString(num);
for (int i = 0; i < number.length(); i++) {
if (count < frequency) {
if (number.charAt(i) == digit)
count++;
}
if (count == frequency)
{
System.out.println(number);
return ;
}
}
}
Using the primes function from an exercise on the Sieve of Eratosthenes, as well as the digits and filter functions from the Standard Prelude, this Scheme expression finds the seven solutions:
(filter
(lambda (n)
(= (length
(filter
(lambda (d) (= d 3))
(digits n)))
4))
(primes 100000))
The outer filter runs over all the primes less than 100000 and applies the test of the outer lambda to each. The inner filter computes the digits of each prime number and keeps only the 3s, then the length function counts them and the equality predicate keeps only those that have 4 3s. You can run the program and see the solution at http://codepad.org/e98fow2u.
you only have at most five digits, four of which must be 3. So what can you say about the remaining digit?
It's not hard to just write out the resulting numbers by hand, and then test each one for primality. Since there are no more than 50 numbers to test, even the simplest trial division by odds will do.
But if you want to generate the numbers programmatically, just do it with 5 loops: add 10,000 to 03333 9 times; add 1,000 to 30333 9 times; add 100 to 33033 9 times; etc. In C++:
int results[50];
int n_res = 0;
int a[5] = {13333, 31333, 33133, 33313, 33331};
for( int i=0, d=10000; i<5; ++i, d/=10)
for( int j=1; j<9; ++j, a[i]+=d )
if( is_prime(a[i]) )
results[n_res++] = a[i];
i want to print first 100 prime numbers. so, i created an array of int 100. I added first prime, bag[0] = 2, then for the following numbers, I tried to write an algorithm. It will start from 3 and goes on until array is full. Every number is decided to be if it is prime by whether it is divisible by the previous elements in array and if it is prime then it will be added to array.
here is my code:
public class Trial02
{
public static void main( String[] args)
{
int[] bag = new int[100];
bag[0] = 2; //first element of prime array
int valid = 1;
int i;
boolean result = true;
String str = "";
//starting from 3 it checks if a number is prime until array is full
for( i=3; valid<bag.length; i++)
{
//it checks if previous primes in array are divisible by current number until coming to current number
for(int k=0; k<valid; k++)
{
if( i % bag[k] == 0)
result = false;
}
if( result == true) //if it is prime it is added to array
{
bag[valid] = i;
valid ++;
}
}
//printing results
for(int m=0; m < bag.length; m++)
str = str + bag[m] + " ";
System.out.println("zaa xd");
System.out.println(str);
}
}
but it don't give any output, just a blank. I couldn't find where my mistake is.
Thanks in advance.
You're never actually checking if a number is prime or not (result isn't being set anywhere useful)
It looks like you need to reset result = true; inside the first for loop. Your code as posted sets result = false and then never changes it.
The most obvious error is that your boolean result = true; is outside the loop: once set to false, it never gets set back to true. You do not see any output because your program never stops.
As a side note, you do not need to check all primes all the way to the last one you've discovered: you can stop once you reach the square root of the candidate prime, i.e. i*i > bag[k]. You are not going to notice any effect when your limit is 100, but if you try 100000, it would help a lot more.
Your logic for determining the first 100 prime numbers is incorrect. And number of logical errors are present as indicated by others. I have re-written your code but not tested. I guess it will work:
public class Trial02
{
public static void main( String[] args)
{
int[] bag = new int[100];
bag[0] = 2; //first element of prime array
int valid = 1;
int i;
boolean isPrime = true;
String str = "";
//starting from 3 it checks if a number is prime until array is full
for( i=3; valid<bag.length; i++)
{
isPrime = true;
for (int k = 2; k < i; k++)
{
if (i % k == 0)
{
isPrime = false;
break;
}
}
if (isPrime == true)
{
bag[valid++] = i;
}
}
//printing results
for(i=0; i < bag.length; i++)
str = str + bag[i] + " ";
System.out.println("zaa xd");
System.out.println(str);
}
}
You have a number of logical mistakes in your code.
First you have a for loop that has a finalization case unrelated to its indexer. While this is valid, it makes the code harder to understand.
More importantly, result is only ever set to false, not true, so thus the loop will run forever, as valid is never changed.