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;
}
}
}
Related
My code doesn't work and i don't know either why or how to make it work. This is my code.
public static void ex5(){
Scanner scan = new Scanner(System.in);
int givenNr = scan.nextInt();
int m = 1;
for (int i = 2; i < givenNr; i++){
while (m <= i/2 ){
if(i % m != 0) {
System.out.print(i + " ");
}
m++;
}
}
}
public static void ex5() {
Scanner scan = new Scanner(System.in);
int givenNr = scan.nextInt();
for (int i = 2; i < givenNr; i++) {
if (isPrime(i))
System.out.println(i);
}
}
public static boolean isPrime(int n) {
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0)
return false;
}
return true;
}
I wrote the code in JAVA and it seems to work fine in Eclipse. But I get an error when I submite the code in SPOJ(runtime error (NZEC) ).
Could someone please help me with this.
Here what I tried so far:
class Main {
public static void main(String[] args) throws java.lang.Exception {
Scanner n1 = new Scanner(System.in);
Scanner n3 = new Scanner(System.in);
int n2 = n1.nextInt();
int[][] n4 = new int[n2][2];
for (int i = 0; i < n2; i++) {
String[] s2 = n3.nextLine().split(" ");
for (int j = 0; j < 2; j++) {
n4[i][j] = Integer.parseInt(s2[j]);
}
}
for (int i = 0; i < n2; i++){
for(int j=n4[i][0];j<=n4[i][1];j++){
if(isPrimeNumber(j)){
System.out.println(j);
}
}
System.out.println();
}
}
public static boolean isPrimeNumber(int number) {
if (number == 2 || number == 3) {
return true;
}
if (number % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(number) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
1st thing you need to do is use the scanner properly and get rid off the 2nd one..
you are using 2 scanners because only one is not working as expected, why?
because you forgot that the Scanner#nextInt method does not consume the last newline character of your input, and thus that newline is consumed in the next call to Scanner#nextLine
Try this:
public static void main(String[] args) throws ParseException {
Scanner input = new Scanner(System.in);
int n2 = input.nextInt();
input.nextLine();
int[][] n4 = new int[n2][2];
for (int i = 0; i < n2; i++) {
String string2 = input.nextLine();
String[] s2 = string2.split(" ");
for (int j = 0; j < 2; j++) {
n4[i][j] = Integer.parseInt(s2[j]);
}
}
for (int i = 0; i < n2; i++) {
for (int j = n4[i][0]; j <= n4[i][1]; j++) {
if (isPrimeNumber(j)) {
System.out.println(j);
}
}
System.out.println();
}
}
public static boolean isPrimeNumber(int number) {
if (number == 2 || number == 3) {
return true;
}
if (number % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(number) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
I'm trying to make a function to give the closest prime number to the number the person entered, and I'm not being successful. By the way, I'm starting to program now and for loops confuse me, any tips?
Here's the code below:
public static void main(String[] args) {
// Entry Mechanism
Scanner input = new Scanner(System.in);
// Variables
int n1, biggestPrime;
System.out.print("Number: ");
n1 = input.nextInt();
biggestPrime = biggestPrime(n1);
}
public static int biggestPrime(int n1) {
int biggestPrime = 0;
boolean isPrime = true;
if (n1 < 0)
return 0;
for (int i = n1; i == 0 && isPrime == false; i--) {
if (i % n1 == 0) {
isPrime = false;
}
}
return biggestPrime;
}
I've supposed that you'll not try to find the biggest prime number of a prime number...
public static void main(String[] args) {
// Entry Mechanism
Scanner input = new Scanner(System.in);
// Variables
int n1, biggestPrime;
System.out.print("Number: ");
n1 = input.nextInt();
biggestPrime = biggestPrime(n1);
}
public static int biggestPrime(int n1) {
int biggestPrime = 0;
int num_max = 100000;
if (n1 < 0) {
return 0;
}
else {
for (int i = n1; i< num_max; i++) {
for (int j = 2; j < Math.sqrt(i); j++) {
System.out.println(j + " " + i);
if (i==j) {
biggestPrime = i;
// break:
j = num_max;
i = num_max;
}
if (i % j == 0) {
break;
}
}
}
}
return biggestPrime;
}
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.
I need to factorize a number like 24 to 1,2,2,2,3. My method for that:
static int[] factorsOf (int val) {
int index = 0;
int []numArray = new int[index];
System.out.println("\nThe factors of " + val + " are:");
for(int i=1; i <= val/2; i++)
{
if(val % i == 0)
{
numArray1 [index] = i;
index++;
}
}
return numArray;
}
however, it is not working. Can anyone help me for that?
You have a few errors, you cannot create int array without size. I used array list instead.
static Integer[] factorsOf(int val) {
List<Integer> numArray = new ArrayList<Integer>();
System.out.println("\nThe factors of " + val + " are:");
for (int i = 2; i <= Math.ceil(Math.sqrt(val)); i++) {
if (val % i == 0) {
numArray.add(i);
val /= i;
System.out.print(i + ", ");
}
}
numArray.add(val);
System.out.print(val);
return numArray.toArray(new Integer[numArray.size()]);
}
Full program using int[] according to your request.
public class Test2 {
public static void main(String[] args) {
int val = 5;
int [] result = factorsOf(val);
System.out.println("\nThe factors of " + val + " are:");
for(int i = 0; i < result.length && result[i] != 0; i ++){
System.out.println(result[i] + " ");
}
}
static int[] factorsOf(int val) {
int limit = (int) Math.ceil(Math.sqrt(val));
int [] numArray = new int[limit];
int index = 0;
for (int i = 1; i <= limit; i++) {
if (val % i == 0) {
numArray[index++] = i;
val /= i;
}
}
numArray[index] = val;
return numArray;
}
}
public int[] primeFactors(int num)
{
ArrayList<Integer> factors = new ArrayList<Integer>();
factors.add(1);
for (int a = 2; num>1; )
if (num%a==0)
{
factors.add(a);
num/=a;
}
else
a++;
int[] out = new int[factors.size()];
for (int a = 0; a < out.length; a++)
out[a] = factors.get(a);
return out;
}
Are you looking a more faster way?:
static int[] getFactors(int value) {
int[] a = new int[31]; // 2^31
int i = 0, j;
int num = value;
while (num % 2 == 0) {
a[i++] = 2;
num /= 2;
}
j = 3;
while (j <= Math.sqrt(num) + 1) {
if (num % j == 0) {
a[i++] = j;
num /= j;
} else {
j += 2;
}
}
if (num > 1) {
a[i++] = num;
}
int[] b = Arrays.copyOf(a, i);
return b;
}
Most of the approaches suggested here have 0(n) time complexity. This can be easily resolved using binary search approach with 0(log n) time complexity.
What do you basically are looking for is called Prime Factors (although 1 is not considered among prime factors).
//finding any occurrence of the no by binary search
static int[] primeFactors(int number) {
List<Integer> al = new ArrayList<Integer>();
//since you wanted 1 in the res adn every no will be divided by 1;
al.add(1);
for(int i = 2; i< number; i++) {
while(number%i == 0) {
al.add(i);
number = number/i;
}
}
if(number >2)
al.add(number);
int[] res = new int[al.size()];
for(int i=0; i<al.size(); i++)
res[i] = al.get(i);
return res;
}
Say input is 24, we keep dividing the input by 2 till all multiples of 2 are gone, the increase i to 3
Here is a link to the working code: http://tpcg.io/AWH2TJ
A Working example
public class Main
{
public static void main(String[] args)
{
System.out.println(factorsOf(24));
}
static List<Integer> factorsOf (int val) {
List<Integer> factors = new ArrayList<Integer>();
for(int i=1; i <= val/2; i++)
{
if(val % i == 0)
{
factors.add(i);
}
}
return factors;
}
}
Rework an algorithm for working with big numbers using BigInteger class. Try this:
import java.math.BigInteger;
class NumbersFactorization {
public void printPrimeNumbers(String bigNumber) {
BigInteger number = new BigInteger(bigNumber);
for (BigInteger i = BigInteger.TWO; i.compareTo(number) <= 0; i = i.add(BigInteger.ONE)) {
while(number.remainder(i) == BigInteger.ZERO) {
System.out.print(i + " ");
number = number.divide(i);
}
}
if (number.compareTo(BigInteger.TWO) > 0) System.out.println(number);
}
}
You just missed one step in if. Following code would be correct:
System.out.println("\nThe factors of " + val + " are:");
You can take a square root of val for comparison and start iterator by value 2
if(val % i == 0)
{
numArray1 [index] = i;
val=val/i; //add this
index++;
}
but here you need to check if index is 2,it is prime.