How to separate integer in loop? [duplicate] - java

This question already has an answer here:
how to separate decimal number? [closed]
(1 answer)
Closed 2 years ago.
When I try to separate decimal from others it work fine with using boolean.
But I doesn't work anymore after another integer come but.
This code is not written by me
String str = "123/0.312/43";
boolean b= false;
for(int i = 0; i < str.length(); i++){
if (b || str.charAt(i + 1) == '.'){
b = true;
System.out.print(str.charAt(i));
} else {
System.out.println(str.charAt(i));
}
}
but it only work like this
1
2
3
/
0.312/43
The number 4 and 3 are another numbers so.
How could I return?
THIS IS THE EXPECTED RESULT THANKS
1
2
3
/
0.312
/
4
3

public static void splitDigits(String str) {
boolean slash = false;
for (String part : str.split("/")) {
if (slash)
System.out.println('/');
slash = true;
if (part.contains("."))
System.out.println(part);
else {
for (int i = 0; i < part.length(); i++)
System.out.println(part.charAt(i));
}
}
System.out.println();
}

Related

Determine if a number contains a specific digit [duplicate]

This question already has an answer here:
Determine if a number contains a digit for class assignment
(1 answer)
Closed 2 years ago.
My idea is to create a loop and not print numbers that contain a 3 in them like 13, 23, 43,etc. between 2 numbers given by a user.
My problem is on the loop. How do I check that the numbers contain a 3 on them?
For example if it prints from 2 to 24. It should not print 3,13 and 23.
for(int i = x; i <= y; i++){
if(i%3 == 0){
System.out.print("");
else{
System.out.println(i);
}
}
for(int i = x; i <= y; i++){
if(i%10 == 3){
System.out.print("");
}
else{
System.out.println(i);
}
}

How to compute a mathematical expression given from a user? [duplicate]

This question already has answers here:
Evaluating mathematical expressions
(5 answers)
How to evaluate a math expression given in string form?
(26 answers)
Closed 3 years ago.
Say A user inputs the following 100 + 12 - 1 / 3
Using Scanner, I get that input and then split it to 100,+,12,-,1,/3
Now what I want to do is calculate the total in the order provided.
112 then 111 then 37 so the answer is 37.
This is my current thought process but now I'm stuck on how to implement it in Java for the rest of the length and operators.
This only work for "1 + 1"
or "1 / 1"
But what I need is for some variable to hold the first 2 integers result and then -,*,/ or add based on the rest of the expression.
Scanner numstr = new Scanner(System.in);
String input = numstr.nextLine();
String [] str = input.split(" ");
int sum =0;
int add =0;
int temp;
for (int i=0;i<str.length;i++) {
if (i%2 >0 && str[i].equals("+"))
{
sum = Integer.parseInt(str[i-1]) + Integer.parseInt(str[i+1]);
//sum = add;
System.out.println(sum);
}
temp =sum;
else if (i%2 >0 && str[i].equals("-"))
{
sum = Integer.parseInt(str[i-1]) - Integer.parseInt(str[i+1]);
//sum = temp - Integer.parseInt(str[i+1]);
System.out.println(sum);
}
//temp = sum;
else if (i%2 >0 && str[i].equals("/"))
{
sum = Integer.parseInt(str[i-1]) / Integer.parseInt(str[i+1]);
System.out.println(sum);
}
else if (i%2 >0 && str[i].equals("*"))
{
sum = Integer.parseInt(str[i-1]) * Integer.parseInt(str[i+1]);
System.out.println(sum);
}
else if (i%2 >0 && !str[i].equals("+")&&!str[i].equals("-")&&!str[i].equals("/")&&!str[i].equals("*"))
{
System.out.println("unknow operator");
}
}
so for 1 + 2 + 5 * 30
would be:
3,
8,
240

Multiply by two then every three years by three

I am working on an assignment that asks:
Magic Plant
We have a magic plant that once it is planted, it germinates and grows two leaves in the first
year. It doubles its leaves every year except that every three years it triples its leaves.
Something like:
Year: 1 | 2 | 3 | 4| 5| 6 | 7 …
Leaves: 2 | 4 | 12| 24| 48|144|288 …
What I have completed so far:
int n = 0;
int l = 6;
for(int i = 2; i>-1; i++) {
if(i == l) {
break;
}
if(i != l) {
n = 2 * i;
}
if(i == l) {
break;
}
if(i != l) {
n = 3 * i;
}
System.out.println(n);
}
My thought process behind that was to check if it passed the year 6 before it multiplied it by two and then by three on the third year, then repeat.
This does not work the output is:
3
6
9
15
I need to be able to input a year and find a number of leaves,
as well as take the number of leaves and find out how old the plant is.
public static void main(String [] args)
{
String years = "";
String leave = "";
int num_years = 10;
int leave_count = 1;
for(int i=1;i<= num_years;i++) {
leave_count = (i%3 == 0)? leave_count * 3:leave_count*2;
years = years + i +"|";
leave = leave + leave_count + "|";
}
System.out.println(years+"\n"+leave);
}
how about this:
int years = 30; //number of years
long leaves = 0; //long is better because int will overflow faster
for(int i = 0 ; i < years ; ++i){
if(i == 0)//first year
leaves += 2;//adds 2 leaves
else if(i % 3 == 0) //Every third year
leaves *= 3; //triple leaves
else//every other year
leaves *= 2; //doubles leaves
System.out.println(leaves);
}
will print:
2
4
8
24
48
96
288
576
...
Test the code here
You could use the mod or remainder operator (%), it's pretty handy for this kind of tasks.
I recommend using better names for your variables since it can be detrimental in the long run; use self explanatory names like numberOfLeaves instead of n and sixthYear instead of l.
Using this knowledge you could get the number of years of the tree, since it's an assignment (for collegue I guess...) I'll not put the code for that but I will give you a hint of a way to do it: substract inside a loop until you have zero leaves.
Here is a recursive way to do it.
private static int[] numberOfLeaves(int year) {
if (year > 1) {
if (year % 3 != 0) {
int[] ret1 = new int[2];
ret1[0] = ++numberOfLeaves(year - 1)[0];
ret1[1] = numberOfLeaves(year - 1)[1] * 2;
return ret1;
} else {
int[] ret2 = new int[2];
ret2[0] = ++numberOfLeaves(year - 1)[0];
ret2[1] = numberOfLeaves(year - 1)[1] * 3;
return ret2;
}
}
int[] ret = new int[2];
ret[0] = year;
ret[1] = year * 2;
return ret;
}
It is tested. When you print out the data, you should access it by index (ret[0] for number of years and ret[1] for number of leaves.).

Java - numbers with at least one 7 and one 9 in its digit

I have to code a program to determine how many positive integers under 1,000,000 have at least one 7 and at least one 9 among its digits by examining the digits in each number from 1 to 999,999 ("brute-force" method). The answer is supposed to be 199,262. Please help!
How about converting the number to a String and text if it contains 7 and 9
int count = 0;
for (int i = 1; i < 1000000; i++) {
String text = String.valueOf(i);
// contains both
if (text.contains("7") && text.contains("9")) count++;
}
System.out.println(count);
Some combinatorics for you:
Number of two digit numbers without a 7 (or without a 9):
8*(9^1) = 72
Number of 2-digit numbers without a 9 or 7:
7*(8^1) = 56
Number of 2-digit numbers:
9*(10^1) = 90
Number of 2-digit numbers with at least one 7 and one 9:
90 - 2*72 + 56 = 2
Formula for n-digit calculation:
= 9*(10^(d-1)) - 2*8*(9^(d-1)) + 7*(8^(d-1))
9*(10^1+10^2+10^3+10^4+10^5)
- 2*8*(9^1+9^2+9^3+9^4+9^5)
+ 7*(8^1+8^2+8^3+8^4+8^5)
= 199262
The brute force algorithm:
public int count() {
int count = 0;
boolean per7 = false;
boolean per9 = false;
for (int i = 0; i < 1000000; i++) {
int j = i;
while ((!(per7 && per9)) && j > 1) {
if (j%10 == 7) {
per7 = true;
} if (j%10 == 9) {
per9 = true;
}
j = j/10;
}
if (per7 && per9) {
count++;
}
per7 = false;
per9 = false;
}
return count;
}
On the other hand, I would suggest using basic knowledge about combinatorics, but I understand that during studies, we often do stupid tasks to learn certain skill.

what is an efficient algorithm in java to verify an prime number with more than 12 digits? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
How to implement an efficient code in java to verify whether a given number is a prime number or not for number's of size greater than or equal to 12 digits?
Example
Input:
100123456789
Output: prime
Input:
101111111111
Output: prime
Input:
101740496633
Output: prime
Input:
111111111111
Output:not prime
Input:
157639024808
Output: not prime
I tried implementing the following algorithm to find whether it is prime or not. But it is not working taking too long for numbers with greater than or equal to 12 digits.
My Code
public static Boolean checkPrime(long a){
if(a%2==0)
return false;
for(int i=3;i<(int)Math.sqrt(a);i=i+2){
if(a%i==0){
return false;
}
}
return true;
}
'a' is the number to be checked
The above function returns true if the given number is prime or false if the given number is not prime.
How to find whether a given number is prime or not for numbers of size greater than 12?
You can speed this up slightly by only checking 1/3 of values instead 1/2.
public static boolean checkPrime(long a) {
if (a % 2 == 0)
return a == 2;
for (int i = 3; i <= (int) Math.sqrt(a); i = i + 2) {
if (a % i == 0) {
return false;
}
}
return true;
}
public static boolean checkPrime2(long a) {
if (a % 2 == 0 || a % 3 == 0 || a % 5 == 0) {
return a <= 3 || a == 5;
}
for (int i = 6, max = (int) Math.sqrt(a); i <= max; i = i + 6) {
if (a % (i + 1) == 0 | a % (i + 5) == 0) {
return false;
}
}
return true;
}
public static void time(String desc, BooleanSupplier run) {
long start = System.nanoTime();
boolean result = run.getAsBoolean();
if (!result)
throw new AssertionError();
long time = System.nanoTime() - start;
System.out.printf("%s took %.3f mill-seconds%n", desc, time / 1e6);
}
public static void main(String... args) {
for (int i = 2; i < 1000; i++) {
boolean a = checkPrime(i);
boolean b = checkPrime2(i);
if (a != b)
throw new AssertionError(i);
}
for (int i = 0; i < 3; i++) {
time("checkPrime", () -> checkPrime(9999999998987L));
time("checkPrime2", () -> checkPrime2(9999999998987L));
}
}
prints
checkPrime took 26.887 mill-seconds
checkPrime2 took 13.878 mill-seconds
checkPrime took 25.527 mill-seconds
checkPrime2 took 11.286 mill-seconds
checkPrime took 16.799 mill-seconds
checkPrime2 took 9.929 mill-seconds
This is starting to get small enough that it's not clear that multiple threads would help.

Categories

Resources