I have been recently started learning Java and would want to make code that sums the numbers from 1 to 100 (result would be 5050)
The code should go like 1+2+3+4+5+6+7+8+9+10... etc
I have tested it with this code:
public class T35{
public static void main(String[] args) {
int nmb;
for(nmb= 1; nmb<= 100; nmb++){
System.out.println(nmb);
}
}
}
But the result is that it goes from 1 to 100 without adding the numbers.
Not sure if it need to be made with while but could not figure the math for it.
Hey you can find the sum from 1 to 100 like this also. Just a option.
You can use the mathematical formula for sum of numbers i.e n(n+1)/2
public class test {
public static void main(String[] args) {
int i =100;
int sum = (i)*(i+1)/2;
System.out.println(sum);
}
}
nmb++ is equal to nmb = nmb + 1. It only adds one till it's 101, which is when it stops.
You should add a new variable, let's call it total, and sum nmb to it every iteration.
public class T35{
public static void main(String[] args) {
int nmb;
int total = 0;
for(nmb= 1; nmb<= 100; nmb++){
total = total + nmb;
}
System.out.println(total);
}
}
This will do what you want.
You have started to learn Java by implementing a for loop. Unfortunately that is probably the least intuitive syntax in the entire language. It was inherited from c and, while convenient, really makes no sense: the meaning of the three positions bears no resemblance to natural language (unlike if, while, implements etc.). Much better to start with simpler constructs until you get the hang of things.
Java 8 provides a more intuitive (in my opinion) way of representing a group of numbers to add. In your case you don't really want to iterate through all the numbers from 1 to 100. You just want a way to represent all those numbers and then sum them. In Java 8 this concept is represented by a stream of integers: the IntStream class. It provides a handy way of asking for 'all integers between x and y': the rangeClosed method. And it provides a method for adding all the integers together: the sum method.
So your operation could be implemented with a single, simple Java statement:
IntStream.rangeClosed(1, 100).sum();
That seems a pretty straightforward statement to read: give me a stream of integers in the range from 1 to 100 and then sum them. Even better you don't need to declare a variable you have no real use for.
You output the value of nmb that is the numeric value that you iterate on, you don't increment the actual value with the current sum.
You should introduce a local variable before the loop to compute and maintain the actual sum.
Besides, int nmb; could be declared directly in the loop.
Narrowing the scope of variables makes the code more robust.
public class T35{
public static void main(String[] args) {
int sum = 0;
for(int i= 1; i<= 100; i++){
sum += i;
System.out.println(sum);
}
}
}
Use this code. It will print the value like
1+2+3.. + 100 = 5050
public class T35{
public static void main(String[] args) {
int total=0;
StringBuilder stringBuilder=new StringBuilder();
for(int nmb= 1; nmb<= 100; nmb++){
total+=nmb;
stringBuilder.append(nmb);
if(nmb!=100)
stringBuilder.append("+");
}
stringBuilder.append(" = "+total);
System.out.println(stringBuilder.toString());
}
}
public class SumsUpPractice2 {
public static void main(String[] args) {
//
int count, sum;
sum = 0;
for (count = 1;count <= 100; count++) {
sum = sum + count;
}
System.out.println(sum);
}
}
We initialize sum with 0 and add count to it at each iteration.
Related
I'm trying to make a simple recursive code that counts the sums of a fibonacci progression but I don't know how to make the counter works properly, this is my code:
public static long fibonacciRecursiveHits(int n,long sum)
{
if (n>1)
{
sum++;
sum = fibonacciRecursiveHits(n-1,sum) + fibonacciRecursiveHits(n-2,sum);
}
return sum;
}
Example:
Input: 4
Correct Output: 4 //The number of sums
My Output: 12
Your problem is that you are computing the number of sums for n AND you are adding it to the sums of n+1 and n+2 which make you count them more than once.
Easy solution : return number of sums
Just count the number of sums for n without passing them down. Try this for example:
public static long fibonacciRecursiveHits(int n)
{
if (n>1)
{
return fibonacciRecursiveHits(n-1) + fibonacciRecursiveHits(n-2) + 1;
} else {
return 0;
}
}
What we are doing here : if n > 1, we count all the sums for n-1 plus the sums for n-2 plus this sum (1 sum).
Alternative : passing a parameter
If you want to pass the sum down as a parameter and update it recursively, you could, but not without a trick since Java is pass-by-value, which means if you modify sum in your function, it won't be modified for the caller.
There are several ways to workaround this.
create an object containing int sum and pass the object down
create a static variable sum, so that you can modify it everywhere in your class
create an array of one element and pass it down
Other ways described in this answer
Here is an example on how to do it with option 3:
public static void fibonacciRecursiveHits(int n, long[] sum)
{
if (n>1)
{
sum[0]++;
fibonacciRecursiveHits(n-1, sum);
fibonacciRecursiveHits(n-2, sum);
}
}
What happens is that every call that does make a sum will increment sum.
Now you call it this way:
long[] sum = {0};
fibonacciRecursiveHits(4, sum);
System.out.println(sum[0]); //sum[0] contains your result
Iterative solution
The problem of the recursive solutions above is that they have exponential running time O(2^n), which mean that would be very slow on medium to large inputs. An alternative is to build the results iteratively and keep them on an array (dynamic programming). This reduces the runtime to O(n).
public static long fibonacciRecursiveHits(int n)
{
long[] sums = new long[n+1];
// sums[0] and sums[1] are both initialized to 0
for(int i = 2; i <= n; i++){
sums[i] = sums[i-2] + sums[i-1] + 1;
}
return sums[n];
}
Could anyone give me some clue about how could I Transform this code to recursion:
public class arrayExample {
public static void main (String[] args) {
int[] a = {2,2,2,2};
int[] b = {2,2,2,2};
int n = a.length;
int sum = 0;
for (int i = 0; i < n; i++) {
sum += a[i] * b[i];
}
System.out.println(sum);
}
}
So to do this do product with recursion.
You asked for a hint, so I'm not giving you the complete solution. When you want to process a list (or an array) recursively, the concept is nearly always:
public int recursiveFunction(List l, int carry) {
if (l.isEmpty()) {
return carry;
}
return recursiveFunction(l.subList(1, l.size()), operation(carry, l.get(0));
}
Where operation is whatever you want to do with your list. carry is used to provide an initial value (in the first call) and save the interim results.
You just have to change the code so it uses two arrays instead of one list and choose the correct operation.
Ok so hoping you have tried it before this is one possible way to code it.
public class ArrayExample {
public static void main (String[] args) {
int[] a = {2,2,2,2};
int[] b = {2,2,2,2};
int n = a.length;
int result = recurseSum(a, b, n-1);
System.out.println(result);
}
public static int recurseSum(int[] a, int[] b, int n){
if(n == 0)
return a[0]*b[0];
else{
return (a[n] * b[n]) + recurseSum(a,b,n-1);
}
}
}
This code is basically doing the same thing in the iteration.
The recursive call happens 4 times. When n hits 0, a[0]*b[0] is returned to the higher call. so basically from right to left it happens as follows:
a[3]*b[3] + a[2]*b[2] + a[1]*b[1] + a[0]*b[0]
One simple way to make a loop into a recursion is to answer these two questions:
What happens when the loop executes zero times?
If the loop has already executed n-1 times, how do I compute the result after the n-th iteration?
The answer to the first case produces your base case; the answer to the second question explains how to do the recursive invocation.
In your case, the answers are as follows:
When the loop executes zero times, the sum is zero.
When the loop executed n-1 times, add a[n] * b[n] to the previous result.
This can be translated into a recursive implementation
static int dotProduct(int[] a, int[] b, int n) {
... // your implementation here
}
I am having trouble printing out the first two columns of the results in a table but as I am new to programming I am having issues and wondering where the issue is in my code. The brief states I must create:
A parameterless static int method, randInt(), that will return a random integer in the range 0..9 inclusive. This method will include a call to Math.random().
A static void method named randTest that takes a single integer argument, n. This should perform the following actions:
Declare an int array of 10 elements named counts. This will be used to record how often each possible value is returned by randInt.
Call randInt n times, each time incrementing the count of the element of counts corresponding to the value returned.
Print the results to the console in a clear tabular form. The output should look like the following:
This is my code:
import java.util.Arrays;
public class RandNumGenerator {
public static int RandInt(){
double n = Math.random()*10;
return (int) n;
}
public static void randTest(int n){
int [] counts = new int [10];
for(int i=0;i<n;i++){
counts[i] = RandInt();
System.out.println(counts[i]);
}
}
public static void main(String[] args) {
int sampleSize = 1000;
System.out.println ("Sample Size: " + sampleSize);
String[] intArray = new String[] {"Value","Count","Expected","Abs Diff","Percent Diff"};
System.out.println(Arrays.toString(intArray));
randTest(10);
}
}
public static void randTest(int n){
Question for you to think about: What is the parameter here? Hint: It's not 10... What do you actually want to DO n times?
counts[i] = RandInt();
You really want to create 10 random numbers and store them into the array? Nope. You want to create "sampleSize" numbers and increase the array on the correct position. What would the correct position be?
counts[ correctPosition ] = counts[ correctPosition ] + 1;
...would be more correct, if you can figure out the correctPosition.
Also I would move the output from the main method to randTest() where you have everything together.
I am having a lot of trouble with this basic recursion problem in java; any pointers would be great.
"Write a static recursive method to print out the nth term of the
geometric sequence: 2, 6, 18, 54."
From what I can gather, somewhere in the code I should be recursively multiplying something by 3, but I'm struggling to figure out how to do this. I know I need a termination statement, but when does that occur? Do I need a helper method?
A Recursive Function is a function whose implementation references itself. Below is some funny example:
public class Inception {
public void dream() {
boolean enoughDreaming = false;
//Some code logic below to check if it's high time to stop dreaming recursively
...
...
if(!enoughDreaming) {
dream(); //Dream inside a Dream
}
}
}
And the solution for your problem:
public class GeometricSequence {
public static void main(String[] args) {
//Below method parameters - 5 = n, 1 = count (counter), res = result (Nth number in the GP.
System.out.println(findNthNumber(5, 1, 2));
}
public static int findNthNumber(int n, int count, int res) {
return ((count == n)) ? res : findNthNumber(n, count+1, res *3);
}
}
EDIT:
The above class uses "int", which is good only for small numbers (because of Integer Overflow problem). The below class is better for all types/numbers:
public class GeometricSequence {
public static void main(String[] args) {
//Below method parameters - 5 = n, 1 = count (counter), res = result (Nth number in the GP.
System.out.println(findNthNumber(2000, 1, new BigInteger("2")));
}
public static BigInteger findNthNumber(int n, int count, BigInteger res) {
return ((count == n)) ? res : findNthNumber(n, count+1, res.multiply(new BigInteger("3")));
}
}
This is the simplest example of recursion.
You need a method declaration.
You need to check if the end has been reached.
Otherwise you need to call the method again with an operation which makes the difference between one term and the next.
Yes, you need a termination condition - basically when you've taken as many steps as you need. So consider how you want to transition from one call to another:
How are you going to propagate the results so far?
What extra state do you need to keep track of how many more steps you need to take?
What are you going to return from the method?
Here's a C# example (I know your doing Java but it's pretty similar)
public static void Recursive(int counter, int iterations, int value, int multiplier)
{
if (counter < iterations)
{
Console.WriteLine(value);
counter++;
Recursive(counter, iterations, (value * multiplier), multiplier);
}
}
So when you run the function you enter the parameters
"counter" will always be 0 when you first call it
"iterations" is the value of n
"value" is your starting value, in your case 2
"multiplier" is how much you want to multiply by each iteration, in your case 3
Every time it runs it will check to see if counter is less than iterations. If it is more, the value is printed, the counter is incremented, the value is multiplied by the multiplier and you add the same parameters back in to the function.
A recursive solution: Seq(1) is the first element of the sequence .... Seq(n-th)
public static void main(String args[]) throws Exception {
int x = Seq(3); //x-> 18
}
public static int Seq(int n){
return SeqRec(n);
}
private static int SeqRec(int n){
if(n == 1)
return 2;
else return SeqRec(n - 1) * 3;
}
Non-Recursive solution:
public static int Non_RecSeq(int n){
int res = 2;
for(int i = 1; i < n; i ++)
res *= 3;
return res;
}
public static void main(String args[]) throws Exception {
int x = Non_RecSeq(3); //x-> 18
}
Hi
this is a factorial method but it prints 0 in the console please help me thanks
public class Demo {
public static void main(String[] args) {
Demo obj = new Demo();
System.out.println(obj.factorial(500));
}
public int factorial(int n) {
int fact = 1;
for (int i = 2; i <= n; i++) {
fact= fact*i;
}
return fact;
}
EDITED:will return Infinity!
public class Demo {
public static void main(String[] args) {
Demo obj = new Demo();
System.out.println(obj.factorial(500));
}
public double factorial(long n) {
double fact = 1;
for (int i = 2; i <= n; i++) {
fact= fact*i;
}
return fact;
}
}
Since 500! equals 1220136825991110068701238785423046926253574342803192842192413588385845373153881997605496447502203281863013616477148203584163378722078177200480785205159329285477907571939330603772960859086270429174547882424912726344305670173270769461062802310452644218878789465754777149863494367781037644274033827365397471386477878495438489595537537990423241061271326984327745715546309977202781014561081188373709531016356324432987029563896628911658974769572087926928871281780070265174507768410719624390394322536422605234945850129918571501248706961568141625359056693423813008856249246891564126775654481886506593847951775360894005745238940335798476363944905313062323749066445048824665075946735862074637925184200459369692981022263971952597190945217823331756934581508552332820762820023402626907898342451712006207714640979456116127629145951237229913340169552363850942885592018727433795173014586357570828355780158735432768888680120399882384702151467605445407663535984174430480128938313896881639487469658817504506926365338175055478128640000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 you can't fit it into an int (which ranges up to 2147483647).
Using an int you can only store up to 12!.
Using a long you'll get up to 20!
Using a double you'll get up to 170!.
By convention 0! equals 1;
Here is a solution using BigInteger:
public static BigInteger factorial(int i) {
if (i == 0) {
return BigInteger.ONE;
}
BigInteger n = BigInteger.valueOf(i);
while (--i > 0) {
n = n.multiply(BigInteger.valueOf(i));
}
return n;
}
There's no way you can fit 500! on a 32-bit int.
For calculations involving large numbers, consider using a double or a BigInteger, depending on whether you want an approximate or an exact answer.
(Actually, for 500!, even a double would not be enough: Double.MAX_VALUE is 1.7976931348623157E+308, which will "only" let you go up to 170!)
There are two things you should be looking into if you need to calculate the factorial function:
1) Memoization. This will dramatically speed up your calculations, since the factorial function has a recursive definition. What you do is cache previous calculations, so when you ask for k!, you can get it in one step by calculating k*((k-1)!) if you have (k-1)! cached.
2) Stirling's approximation. If you need to calculate large factorials, you can approximate them very rapidly this way, and with guaranteed bounds on the error, so you can tell whether the approximation will be acceptably close for your application.
If you do neither of these, you will find that there is some relatively small k for which you simply can't calculate k! in a reasonable amount of time.
Grodriguez is right - this is almost certainly caused by integer overflow.
If you test your method with more modest inputs it appears to return the right output:
public static void main(String[] args) {
Demo obj = new Demo();
for (int i = 0; i < 10; i++)
System.out.println(i + "! = " + obj.factorial(i));
}
500! is massive; when testing your function, starting with smaller inputs would be prudent.
500! is way too big to fit a long, or double.
You would have to use other techniques to get this.
But first, what kind of program needs 500!?
There are some very nice optimization for the implementation of factorizations: see for instance luschny.de for a nice implementation of them in Java. Some require more mathematical insight then others... Have fun with the library :-)