Checking divisibility of a range of numbers with no repetition of digits - java

I wrote the following program to count the numbers that are divisible by 12 but contain no repetition of digits. eg. the number 144 is not to be considered even though it is divisible by 12 as a repetition of digit 4 is present. The problem is that I get no output. I tried changing the range of for loop from 12...54321 to 12...1000 and even 12...24. I still get no output. I can't seem to find what the problem is. Can someone please tell me what is wrong with my code. Or just suggest me a better code/solution to the problem. Thanks...
class mod12
{
public static void main(String[] args)
{
int count=0;
for(int num=12;num<=54321;num+=12)
{
boolean repetition=false;
int digits[]=new int[10];
int length=0;
while (num!=0)
{
digits[length++]=num%10;
num=num/10;
}
for(int i=0; i<length; i++)
{
for(int j=0; j<length; j++)
{
if(i!=j)
{
if(digits[i]==digits[j])
{
repetition=true;
break;
}
}
}
}
if(repetition==false)
{count++;}
}
System.out.println("There are "+count+" numbers satisfying the condition");
}
}

In the while loop you decrease num, effectively moving the for loop backwards, so it never completes. Using a temporary variable instead would solve the problem:
public static void main(String[] args)
{
int count=0;
for(int num=12;num<=54321;num+=12)
{
boolean repetition=false;
int digits[]=new int[10];
int length=0;
int tempNum = num; // Here
while (tempNum !=0)
{
digits[length++]=tempNum %10;
tempNum =tempNum /10;
}
for(int i=0; i<length; i++)
{
for(int j=0; j<length; j++)
{
if(i!=j)
{
if(digits[i]==digits[j])
{
repetition=true;
break;
}
}
}
}
if(repetition==false)
{count++;}
}
System.out.println("There are "+count+" numbers satisfying the condition");
}
EDIT:
Regardless of the original question, note you can shorten your code considerably by using a Set to track the digits:
public static void main(String[] args) {
int count = 0;
NUMBERS:
for (int num = 12; num <= 54321; num += 12) {
Set<Integer> digits = new HashSet<>();
int tempNum = num;
while (tempNum != 0) {
int digit = tempNum % 10;
if (!digits.add(digit)) {
continue NUMBERS;
}
tempNum = tempNum / 10;
}
++count;
}
System.out.println("There are "+count+" numbers satisfying the condition");
}

Related

How to solve error java.lang.ArithmeticException when finding prime numbers 1 to 100

When the program is finding the prime numbers, it compiles.
But an error occurred during runtime. How can I fix it ?
What is the easiest way of finding prime numbers?
Error :
Exception in thread "main" java.lang.ArithmeticException: / by zero
at PrimeNumbers.main(PrimeNumbers.java:6)
Code :
import java.util.*;
class PrimeNumbers {
public static void main(String args[]) {
for (int i = 0; i <= 100; i++) {
for (int j = 0; j < i; j++) {
if (i % j == 0) {
break;
} else {
System.out.println(i);
}
}
}
}
}
You must change your code like this:
class PrimeNumbers{
public static void main(String args[])
{
boolean flag;
for(int i=1;i<=100;i++)
{
flag = true;
for(int j=2;j<=(i/2);j++){
if(i%j==0)
flag = false;;
if(flag == true)
System.out.println(i);
}
}
You need to change your second for loop to start from 1 not 0. Because modular of zero is an error.
for(int j=1;j<i;j++){
if(i%j==0){
You have i = 0 and j = 0 in the first iteration of your loop. In order to obtain the modulus, i is divided by j. Therefore, you are performing in the first iteration:
0 / 0
Thus getting the divide by zero exception.
public static void main(String args[]){
boolean flag=false;
int i=1;
while(i<=100){
for(int j=2;j<=i/2;j++) {
if(i%j==0){
flag=true;
break;
}else {
flag=false;
}
}
if(flag!=true) {
System.out.println("Prime number--->" +i);
}
i++;
}
}
There are two possible ways of prime number calculation:
public static boolean isPrime(long num) {
return num > 1 && LongStream.rangeClosed(2, (long)Math.sqrt(num)).noneMatch(div -> num % div == 0);
}
public static boolean isPrime1(long num) {
for (long i = 2, sqrt = (long)Math.sqrt(num); i <= sqrt; i++)
if (num % i == 0)
return false;
return true;
}
Main performance trick is enough to check first Math.sqrt(num) numbers only.

Program to input a number and if its a factorial number then output factorial series else false

import java.util.*;
class Factorial{
void factNum(int n){
int fact=1;
ArrayList<Integer> al=new ArrayList<Integer>();
for(int i=1;fact<=n;i++){
fact=fact*i;
al.add(i);
if(fact==n){
for(int j:al){
System.out.print(+j);
}}
}
}
public static void main(String args[]){
Scanner scan=new Scanner(System.in);
Factorial f=new Factorial();
System.out.println("Enter the Integer");
int num=scan.nextInt();
f.factNum(num);
}
}
I wrote this code so that when I input number 24 which is factorial I will get 1 2 3 4 as a output and when I input 23 i should get output as false. My code is almost correct but the problem is that when I enter number which does not belong to factorial series, I am not getting False as output. Please can anyone help me where in this code I can keep System.out.print("False"); Statement.
You are not printing "False" anywhere.Keep a boolean flag to check if the given number is factorial or not and print accordingly.
void factNum(int n){
int fact=1;
boolean flag = true;
ArrayList<Integer> al=new ArrayList<Integer>();
for(int i=1;fact<=n;i++){
fact=fact*i;
al.add(i);
if(fact==n){
flag = false;//if factorial then make it false
for(int j:al){
System.out.print(+j);
}}
}
if(flag)
System.out.println("False");
}
You can use flag value as shown in below code to keep track of the condition of whether the number is factorial or not.
public static void factNum(int n) {
int fact = 1;
ArrayList<Integer> al = new ArrayList<Integer>();
boolean flag = false;
for (int i = 1; fact <= n; i++) {
fact = fact * i;
al.add(i);
if (fact == n) {
flag = true;
for (int j : al) {
System.out.print(+j);
}
}
}
if(!flag)
System.out.println("false");
}
Try this code.
void factNum(int n) {
int fact = 1;
ArrayList<Integer> al = new ArrayList<Integer>();
int check = 0;
for (int i = 1; fact <= n; i++) {
fact = fact * i;
al.add(i);
if (fact == n) {
for (int j : al) {
System.out.print(+j);
check = 1;
}
}
else if (fact>n && check == 0)
{
System.out.println("False");
}
}
}

Generating 10 random numbers without duplicate with fundamental techniques

my intend is to use simplest java (array and loops) to generate random numbers without duplicate...but the output turns out to be 10 repeating numbers, and I cannot figure out why.
Here is my code:
int[] number = new int[10];
int count = 0;
int num;
while (count < number.length) {
num = r.nextInt(21);
boolean repeat = false;
do {
for (int i=0; i<number.length; i++) {
if (num == number[i]) {
repeat = true;
} else if (num != number[i] && i == count) {
number[count] = num;
count++;
repeat = true;
}
}
} while (!repeat);
}
for (int j = 0; j < number.length; j++) {
System.out.print(number[j] + " ");
}
How about you use a Set instead? If you also want to keep track of the order of insertion you can use a LinkedHashSet.
Random r = new Random();
Set<Integer> uniqueNumbers = new HashSet<>();
while (uniqueNumbers.size()<10){
uniqueNumbers.add(r.nextInt(21));
}
for (Integer i : uniqueNumbers){
System.out.print(i+" ");
}
A Set in java is like an Array or an ArrayList except it handles duplicates for you. It will only add the Integer to the set if it doesn't already exist in the set. The class Set has similar methods to the Array that you can utilize. For example Set.size() is equivalent to the Array.length and Set.add(Integer) is semi-equivalent to Array[index] = value. Sets do not keep track of insertion order so they do not have an index. It is a very powerful tool in Java once you learn about it. ;)
Hope this helps!
You need to break out of the for loop if either of the conditions are met.
int[] number = new int[10];
int count=0;
int num;
Random r = new Random();
while(count<number.length){
num = r.nextInt(21);
boolean repeat=false;
do{
for(int i=0; i<number.length; i++){
if(num==number[i]){
repeat=true;
break;
}
else if(i==count){
number[count]=num;
count++;
repeat=true;
break;
}
}
}while(!repeat);
}
for(int j=0;j<number.length;j++){
System.out.print(number[j]+" ");
}
This will make YOUR code work but #gonzo proposed a better solution.
Your code will break the while loop under the condition: num == number[i].
This means that if the pseudo-generated number is equal to that positions value (the default int in java is 0), then the code will end execution.
On the second conditional, the expression num != number[i] is always true (otherwise the code would have entered the previous if), but, on the first run, when i == count (or i=0, and count=0) the repeat=true breaks the loop, and nothing else would happen, rendering the output something such as
0 0 0 0 0 0...
Try this:
int[] number = new int[10];
java.util.Random r = new java.util.Random();
for(int i=0; i<number.length; i++){
boolean repeat=false;
do{
repeat=false;
int num = r.nextInt(21);
for(int j=0; j<number.length; j++){
if(number[j]==num){
repeat=true;
}
}
if(!repeat) number[i]=num;
}while(repeat);
}
for (int k = 0; k < number.length; k++) {
System.out.print(number[k] + " ");
}
System.out.println();
Test it here.
I believe the problem is much easier to solve. You could use a List to check if the number has been generated or not (uniqueness). Here is a working block of code.
int count=0;
int num;
Random r = new Random();
List<Integer> numbers = new ArrayList<Integer>();
while (count<10) {
num = r.nextInt(21);
if(!numbers.contains(num) ) {
numbers.add(num);
count++;
}
}
for(int j=0;j<10;j++){
System.out.print(numbers.get(j)+" ");
}
}
Let's start with the most simple approach, putting 10 random - potentially duplicated - numbers into an array:
public class NonUniqueRandoms
{
public static void main(String[] args)
{
int[] number = new int[10];
int count = 0;
while (count < number.length) {
// Use ThreadLocalRandom so this is a contained compilable unit
number[count++] = ThreadLocalRandom.current().nextInt(21);
}
for (int j = 0; j < number.length; j++) {
System.out.println(number[j]);
}
}
}
So that gets you most of the way there, the only thing you know have to do is pick a number and check your array:
public class UniqueRandoms
{
public static void main(String[] args)
{
int[] number = new int[10];
int count = 0;
while (count < number.length) {
// Use ThreadLocalRandom so this is a contained compilable unit
int candidate = ThreadLocalRandom.current().nextInt(21);
// Is candidate in our array already?
boolean exists = false;
for (int i = 0; i < count; i++) {
if (number[i] == candidate) {
exists = true;
break;
}
}
// We didn't find it, so we're good to add it to the array
if (!exists) {
number[count++] = candidate;
}
}
for (int j = 0; j < number.length; j++) {
System.out.println(number[j]);
}
}
}
The problem is with your inner 'for' loop. Once the program finds a unique integer, it adds the integer to the array and then increments the count. On the next loop iteration, the new integer will be added again because (num != number[i] && i == count), eventually filling up the array with the same integer. The for loop needs to exit after adding the unique integer the first time.
But if we look at the construction more deeply, we see that the inner for loop is entirely unnecessary.
See the code below.
import java.util.*;
public class RandomDemo {
public static void main( String args[] ){
// create random object
Random r = new Random();
int[] number = new int[10];
int count = 0;
int num;
while (count < number.length) {
num = r.nextInt(21);
boolean repeat = false;
int i=0;
do {
if (num == number[i]) {
repeat = true;
} else if (num != number[i] && i == count) {
number[count] = num;
count++;
repeat = true;
}
i++;
} while (!repeat && i < number.length);
}
for (int j = 0; j < number.length; j++) {
System.out.print(number[j] + " ");
}
}
}
This would be my approach.
import java.util.Random;
public class uniquerandom {
public static void main(String[] args) {
Random rnd = new Random();
int qask[]=new int[10];
int it,i,t=0,in,flag;
for(it=0;;it++)
{
i=rnd.nextInt(11);
flag=0;
for(in=0;in<qask.length;in++)
{
if(i==qask[in])
{
flag=1;
break;
}
}
if(flag!=1)
{
qask[t++]=i;
}
if(t==10)
break;
}
for(it=0;it<qask.length;it++)
System.out.println(qask[it]);
}}
public String pickStringElement(ArrayList list, int... howMany) {
int counter = howMany.length > 0 ? howMany[0] : 1;
String returnString = "";
ArrayList previousVal = new ArrayList()
for (int i = 1; i <= counter; i++) {
Random rand = new Random()
for(int j=1; j <=list.size(); j++){
int newRand = rand.nextInt(list.size())
if (!previousVal.contains(newRand)){
previousVal.add(newRand)
returnString = returnString + (i>1 ? ", " + list.get(newRand) :list.get(newRand))
break
}
}
}
return returnString;
}
Create simple method and call it where you require-
private List<Integer> q_list = new ArrayList<>(); //declare list integer type
private void checkList(int size)
{
position = getRandom(list.size()); //generating random value less than size
if(q_list.contains(position)) { // check if list contains position
checkList(size); /// if it contains call checkList method again
}
else
{
q_list.add(position); // else add the position in the list
playAnimation(tv_questions, 0, list.get(position).getQuestion()); // task you want to perform after getting value
}
}
for getting random value this method is being called-
public static int getRandom(int max){
return (int) (Math.random()*max);
}

Muti threaded program that displays all prime numbers smaller than one entered

I'm trying to write a program that displays all prime numbers below the one entered by the user. The only requirement is that it must be multi threaded. This is my first time using Java and multiple threads. Can you help? It compiles, but the output is strange. Maybe it's an address?
import java.util.Scanner;
import java.util.Arrays;
public class prime {
public static void main(String[] args){
// get number from user
System.out.println("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
int num = keyboard.nextInt();
RunPrime runprime1 = new RunPrime (num);
runprime1.start();
Thread.yield();
runprime1.SmallerPrimeNumbers();
}
}
class RunPrime extends Thread {
private int given_number;
RunPrime (int n) {
given_number = n;
}
public void SmallerPrimeNumbers() {
int count = 0;
for (int i = 0; i <= given_number; i++) {
if (CheckPrime(i)) {
count++;
}
}
for (int i = 0; i < count; i++) {
for (int j = 2; j <= given_number; j++) {
if (CheckPrime(j)) {
number[i] = j;
}
}
}
System.out.println(number);
}
public static boolean CheckPrime (int n) {
for (int i=2 ; i<n ; i++) {
if (n%i == 0)
return false;
}
return true;
}
}
Your SmallerPrimeNumbers() function has a second for-loop that doesn't look necessary. You're also assigning and printing the variable number that wasn't declared anywhere (this is probably what's causing you trouble). Since you're only printing them and not saving them, you can simplify the function like this:
public void SmallerPrimeNumbers() {
int count = 0;
for (int i = 0; i <= given_number; i++) {
if (CheckPrime(i)) {
System.out.println(i);
}
}
}

Print Fibonacci sequence up to nth place?

I am trying to print the entire fibonacci sequence up to a given place. So the user would decide how many numbers of the fibonacci sequence they want to see (up to 16 repetitions) and it would print the entire sequence.
My current code only prints the number in the sequences for the place that you choose.
ex: 4 prints 2 instead of 0 1 1 2.
public int Fibonacci(int number){
if(number == 1 || number == 2){
return 1;
}
int fib1=1, fib2=1, fibonacci=1;
for(int count= 3; count<= number; count++){
fibonacci = fib1 + fib2;
fib1 = fib2;
fib2 = fibonacci;
}
return fibonacci;
}
Here is my main method:
import java.util.Scanner;
public class FibonacciPrinter
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter an integer: ");
int input = in.nextInt();
FibonacciGenerator newNumber = new FibonacciGenerator();
for(int fibCount = 0; fibCount < input; fibCount++)
{
System.out.println(newNumber.Fibonacci(input));
}
}
}
I think here,
for(int fibCount = 0; fibCount < input; fibCount++)
{
System.out.println(newNumber.Fibonacci(input));
}
You almost certainly wanted,
for(int fibCount = 0; fibCount < input; fibCount++)
{
System.out.println(newNumber.Fibonacci(fibCount)); // <-- fibCount not input
}
You need to update your method to handle the zero case, for example
public int Fibonacci(int number) {
if (number == 0) return 0;
// ...
}
and in Java, the convention would name Fibonacci to fibonacci because method names are camel case starting with a lower case letter (classes start with a capital letter by convention).

Categories

Resources