Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am currently taking a HS course on java, so I am a novice at java to say the least. Right now, for my own use, I am writing a program to take a 2 digit number, and then add up it and all the odd numbers before it till 1. I have the Scanner, calculating whether the number is odd or even, and the runner methods done already(the basic bit), but am a bit confused on the logic. I am trying to use a recursion, and do this code, but am a bit stuck. It would be helpful if you could point me in the right direction, without giving the whole code away. Thanks, - A Novice Programmer
public static void main(String[] args)
{
MathRecursion tester = new MathRecursion();
tester.Method1Runner();
}
public void Method1Runner()
{
GetIntM1();
OddOrEven();
System.out.println("\n\n");
}
public void GetIntM1()
{
Scanner kb = new Scanner(System.in);
System.out.print("\n\n\nEnter a 2 digit integer: ");
twoDig = kb.nextInt();
}
public void OddOrEven()
{
if (twoDig % 2 == 0)
{
//This is even method
Method1a(twoDig);
}
else
{
//This is odd method
Method1b(twoDig);
}
}
public int Method1a(int a)
{
//if (a = 1)
int result = 0;
while (a<=b)
{
result+=a;
a++;
}
System.out.println("The sum of all numbers is "+result);
}
You don't need recursion. The sum of the first n odd numbers is n*n.
The number of odd numbers before a number x is floor(x/2) or in Java (int) x/2 or if x is an int, just x/2.
So the expression in Java that gives you "a 2 digit number, and then add up it and all the odd numbers before it till 1" where the number is stored in int x is:
x + (x/2) * (x/2)
or simplified:
x + x*x/4
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
PROBLEM DESCRIPTION
Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate all prime numbers between two given numbers!
Input
The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.
Output
For every test case print all prime numbers p such that m <= p <= n, one number per line, test cases separated by an empty line.
Example
Input:
2
1 10
3 5
Output:
2
3
5
7
//----------BLANK SPACE BETWEEN TEST CASES-------------
3
5
import java.util.*;
import java.lang.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for(int i=0;i<t;i++)
{
boolean prime = true;
long m = in.nextLong();
long n = in.nextLong();
if(m<2)
{
System.out.println("2");
m=3;
}
for(int j=m;j<=n;j+=2)
{
int z = (int)Math.floor(Math.sqrt(j));
for(int k=2;k<=z;k++)
{
if(j%k==0)
{
prime=false;
break;
}
}
if(prime)
System.out.println(j);
}
System.out.println();
}
}
}
Your loops are using int datatype. It is lossy because you are comparing long with int. It will work for small numbers but constraints are too big so try using long.
Edit
I thought its because overflow without running it.
Your code has lots of problems
It will not work when m is even
you are not setting prime back to true in loop
Check these suggestions and comment is it working?
Solution
use long datatype in loop (that is not necessary)
set prime = true in inner loop
instead of incrementing by 2 i.e. j+=2, increment by 1 j+=1.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have this code which I want to use to find prime numbers:
public class Primzahlen {
public static void main(String [] args) {
for(int i = 1;i<100;i++) {
for(int j=1;j<i;j++) {
if(i%j == 0) {break;}
if(j== (i-1)) {System.out.println(i);}
}
}
}
}
But if I try to run the program the output is empty.
The problem with your code is this that, j start from 1 and every number satisfies i%j and the loop breaks so j should start from 2. I would recommend this code which is more effective and runs in O(sqrt(n)) time :
public class Primzahlen {
public static void main(String [] args) {
for(int i = 2;i<100;i++) {
for(int j=2; j < ((int)Math.sqrt(i))+2 ; j++) {
if(i%j == 0) {break;}
if(j== ((int)Math.sqrt(i))+1) {System.out.println(i);}
}
}
}
}
Here are some suggestions.
Seed the first prime as 2. Since 2 is the only even prime this allows subsequent candidates to be just the odd numbers. So starting with 3, increment the candidates by 2.
Only check the primes up to the square root of the candidate.
Since you are finding primes, use the ones already found as the divisors to test for primality. Say the candidate is 17. Primes 2,3,5,7,11,13 have already been found. By applying the previous square root rule, all you need to do is see if 17 is divisible by 3, or 5, and not 2 thru 16. If it were divisible by any prime greater than its square root, it would have already been detected.
For a completely different approach, check out The Sieve of Eratosthenes.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
Edit: I have found a way to work with CompareTo to help with this problem, but for some reason I cannot get the count down to work.
It's a negative number that needs to get more negative to meet the requirements, but I am missing something here. When I execute the down section it closes the program. So to me this means that I have something messed up and the program isnt seeing the problem and closing.
We are supposed to:
Ask the user for an integer then ask the user if he/she wants to count
up or down. Display a table of numbers where the first column contains
the counter, the second column contains the counter plus 10, and the
third column contains the counter plus 100. Make it so each number
takes up 5 spaces total.
If counting up, the first column should contain numbers 1 through the
user input; If counting down, the first column should contain numbers
-1 through the the negative of the user input;
Do user input validation on the word "up" and "down". Allow for any
case.
import java.util.Scanner;
public class ps1 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
//Comparision string already declared
String up = "up";
String down = "down";
//initialize the counters sum
int sum = 0;
//ask the user for a number
System.out.println("Enter an ending value");
int num1 = keyboard.nextInt();
keyboard.nextLine();
System.out.println("Count up or down?");
String input = keyboard.nextLine();
while (input.equalsIgnoreCase(up) || input.equalsIgnoreCase(down)) {
System.out.println("Count up or down?");
input = keyboard.nextLine();
}
if (input.compareToIgnoreCase(up) == 0) {
if (num1 >= 0)
for (int c = 1; c <= num1; c++) {
sum = sum + c;
System.out.printf("%5d%5d%5d\n", c, c + 10, c + 100);
else
System.out.println("Up numbers must be positive");
if (input.compareToIgnoreCase(down) == 0) {
for (int c1 = -1; c1 <= num1; c1--) {
sum = sum + c1;
System.out.printf("%5d%5d%5d\n", c1, c1 + 10, c1 + 100);
}
}
}
}
}
I see you have figured out core logic. BTW, your code will not compile, there is a syntax error.
Your code would look like this:
print(a a+10 a+100)
I know that it's not valid syntax but you would be able to figure out the correct way to write the code.
To print data properly, you will need following:
https://dzone.com/articles/java-string-format-examples
I would recommend visualizing the output first. In your case, it would look like following: (_are spaces)
Enter an ending value: 2
Direction: Up
____1___11__101
____2___12__102
Also, think about error cases. What will happen in following:
Enter an ending value: -10
Direction: Up
Error: Improper data
You are allowing user to enter a positive num1 and count down using for (int counter1 = -1; counter1 >= num1; counter1--). This makes no sense as counter1 >= num1 resolves to -1 >= 1 which is never true. When direction is down the number must be negative and when direction is up the number must be positive.
You might need to loop until user provides a valid direction. Currently you go down for any input that is not up. A possible solution would be to:
String input;
do {
input = keyboard.nextLine();
} while (!input.equalsIgnoreCase("up") && !input.equalsIgnoreCase("down"));
Please use shorter variable names. counter1 is scoped just to the for loop block so call it i. It's easier to read.
Whichever editor you are using configure auto formatting :)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
https://projecteuler.net/problem=4
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
Here is my code and I find the answer as 580085 but it is not the correct answer:
public class asdas {
public static void main(String[] args) {
int a=100,b=100,answer=0;
while(a<=999)
{
b=100;
while(b<=999)
{
int product=a*b;
int reverse=0;
while(product>0)
{
int lastDigit=product%10;
reverse=(reverse*10)+lastDigit;
product=product/10;
}
product=a*b;
if(product==reverse)
{
answer=product;
}
b++;
}
a++;
}
System.out.println(answer);
}
}
The problem is here:
if(product==reverse)
{
answer=product;
}
You're assuming that if you find a palindrome, it's the largest. That's not true though.
For example, 101*100 is calculated after 100*102, even though the latter is larger. In fact, right after calculating 998*999 (997,002), you calculate 999*100 (99,900), which is nearly 10 times smaller!
You should add another check to make sure the new product is greater:
if(product==reverse && product>answer) {
answer = product;
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
So I have this small method I am working on for class and this question is a tough one and a bit confusing. Basically what I have to to is write a method that will take a number that you input and it will find the next prime number that is 1 greater than a squared number. For example if I were to type in 10 the result would be 17, because 17 is a prime number and its 1 greater than a square, the square being 16. So I have to write a method with only one return statement in it to do this, and I have absolutely no idea where to start. What I have so far ispublic static int nextSquarePlus1Prime(int num){
} Literally. Some helped would be greatly appreciated.
I already have this method where I check if the number is prime or not:
public static boolean isPrime(int num){
int i;
boolean numberIsPrime=true;
if(num==1){
numberIsPrime=false;
}
for(i=2;i*i<=num;i++){
if(num%i==0){
numberIsPrime=false;
}
}
return numberIsPrime;
}
Is there a way to add to this method with another piece of code to work alongside with this one to check if the number is a square?
So this is what i came up with for my code and i put in 10 as my number. I'm getting 50 when I should be getting 17.
public static int nextSquarePlus1Prime(int num){
int i;
int save=0;
for(i=1;i<=num;i++){
if(isPrime(i)&& i*i+1>=num){
save=i*i+1;
}
}
return save;
}
The sqrt() method may help. Here is an idea of how to use it:
int squareRoot = (int) Math.sqrt((double) input);
Input being the number you want to round. Casting the result to an int will automatically round it. It is optional. I cast the input to a double, but you only need to do so if your input in an int.
Here is an easier way to check if a number is prime:
if (input % 2 == 0){
input += 1;
}
return input;
I reccomend you look at #useSticks answer again. Using the approach he described I created a method that does exactly what I think you want.
Here is a method that finds the square root of a positive number:
public static int sqrt(double number){
double g1;
if(number==0){
return 0;
}
double squareRoot = number/2;
do{
g1=squareRoot;
squareRoot = (g1 + (number/g1))/2;
}while((g1-squareRoot)!=0);
return (int) squareRoot;
}
You should provide some additional details for more specific pointers.
In Java, there is a method "is probable prime" that may be of use to you.
Its easier to square a number than it is to find the square root, so it may make sense to find the square root of the starting number, then round up. Take that number and square it, add 1 and check for prime. If not, add 1 to the variable and try again.
Good luck.