Trying to get the summing to stop at 100. When I run the program as it is, it sums all the way to 5050.
public class IntSum {
public static void main(String[] args) {
int sum = 0;
int n = 100;
for (int i=1;i<=n;i++) {
sum = sum+i;
System.out.println("Sum = " +sum);
}
}
}
The for loop can use any boolean expression as the check, it doesn't always have to be the format of i < x. For example:
for (int i = 1; sum < 100; i++) {
sum = sum + i;
}
Use an if-statement inside your loop. If the sum exceeds 100, break to for-loop
Related
I don't know what is the problem with my code. It should print all the perfect numbers between 1-100. I tried with nested for-loop, do while loop and for-loop. However, the code seems to be incorrect.
class CompProject1
{
public static void main()
{
int num, sum=0;
int i;
for(num=1; num<100; num++)
{
for(int j = 1; j<=num ; j++)
{
if(num%j==0)
{
sum = sum+j;
}
}
if(sum==num)
{
System.out.println(sum);
}
}
}
}
Change your code to :
public static void main(String[] s1) throws Exception {
int num, sum = 0;
int i;
for (num = 1; num < 100; num++) {
for (int j = 1; j <= num - 1; j++) { // change made here
if (num % j == 0) {
sum = sum + j;
}
}
if (sum == num) {
System.out.println(sum);
}
sum = 0; // change made here
}
}
Key takeaways:
Reset sum to 0 once done with inner iteration
In your inner for-loop you need to check if till num - 1 and not num because every number is divisible by itself
1) you definitely need to reset your sum variable for every iteration, so you should do int sum = 0; in every loop.
2) you need to iterate while j <= num/2;!
3) consider using Java 8, I'll write some sample here for you.
See my example here, this is so beautiful:
public class PerfectNumbersDemo {
public static void main(String[] args) {
IntStream.range(1, 100)
.filter(PerfectNumbersDemo::isPerfect)
.forEach(System.out::println);
}
private static boolean isPerfect(int number) {
return number == IntStream.rangeClosed(1, number / 2)
.filter(i -> number % i == 0)
.sum();
}
}
This seems to be an assignment or homework question. You are meant to solve this by yourself and not ask it to the people on Stack overflow.
However, what you are looking for has an answer here. Beware! This code prints if the input number is perfect number or not but does not print all the numbers below 100 that could be perfect numbers. That is your homework.
You need to:
sum = 0 with every loop iteration
iterate until < num and not <= num
Here's the fixed code:
public static void main(String[] args) {
int sum;
for(int num = 1; num < 100; num++) {
sum = 0;
for(int j = 1; j< num; j++) {
if(num % j == 0) {
sum += j;
}
}
if(sum == num) {
System.out.println(sum);
}
}
}
Output:
6
28
So, your code have some minor problems and I will try to pinpoint them out.
1.First of all your sum variable should be inside the first for loop
2. The limit upto which the second loop will run will be j<num not j<=num because, for the perfect number, the number itself shouldn't be counted in the sum.
You code will look like this.
I don't know what is the problem with my code. It should print all the perfect numbers between 1-100. I tried with nested for-loop, do while loop and for-loop. However, the code seems to be incorrect.
class CompProject1 {
public static void main()
{
int num;
for(num=1; num<100; num++)
{
int sum = 0;
for(int j = 1; j<=num ; j++)
{
if(num%j==0)
{
sum = sum+j;
}
}
if(sum==num)
{
System.out.println(sum);
}
}
}
}
public class factors{
public static void main(String args[]){
int sum=0;
for(int k=2;k<=30;k++){
for(int i=1;i<k;i++)
{
if(k%i==0)
sum=sum+i;
}
if(k==sum)
System.out.println(sum);
sum=0; //sum=0 is very important.
}
}
}
OUTPUT
6
28
class PERFECT
{
public static void main(String args[])
{
int i,j,S,
for(i=1;i<=100;i++)
{
S=0
for(j=1;j<i;j++)
{
if(i%j==0)
S+=j;
if (S==i)
System.out.println(i+"is perfect");
}
}
}
}
Here is an alternate way of finding perfect numbers.
if 2p-1 is prime when p is prime. Then (2p-1)(2p-1) is a perfect number. 2p-1 is known as a Mersenne Prime
As these numbers get real big real fast, using BigInteger is recommended.
This computes the first 10 perfect numbers.
int N = 10;
int count = 1;
for(int i = 2; i < 10_000; i += i == 2 ? 1 : 2) {
BigInteger val = BigInteger.valueOf(i);
if (val.isProbablePrime(99)) {
BigInteger mersenne1 = (BigInteger.ONE.shiftLeft(i)).subtract(BigInteger.ONE);
if (!mersenne1.isProbablePrime(99)) {
continue;
}
BigInteger mersenne2 = BigInteger.ONE.shiftLeft(i-1);
System.out.printf("%3d: %,d\n",count, mersenne1.multiply(mersenne2));
if (count++ >= N) {
break;
}
}
}
prints
1: 6
2: 28
3: 496
4: 8,128
5: 33,550,336
6: 8,589,869,056
7: 137,438,691,328
8: 2,305,843,008,139,952,128
9: 2,658,455,991,569,831,744,654,692,615,953,842,176
10: 191,561,942,608,236,107,294,793,378,084,303,638,130,997,321,548,169,216
I'm actually about to loose my mind... The code I wrote displays every kind of "sum" and "count" between the actual last result I want to display with System.out.print(...). Can someone help me please? What did I do wrong for it to display everything?
public class Prim {
public static void main(String[] args) {
int end = 11;
int count = 1;
long sum = 0;
for (int number = 10; count<=end; number++) {
if (isPrim(number)) {
sum = sum + number;
count++;
System.out.println(sum);
}
}
}
public static boolean isPrim(int number){
for (int i=2; i<number; i++) {
if (number % i == 0) {
}
}
return true;
}
}
A few things.
First, your isPrim can be optimised so that i only increments until sqrt(number).
Second, you need to return false if (number%i == 0) is true. Right now, it's always returning true, which is why your code is outputting all sums.
Third, you need to change istPrimeZahl to isPrim (or vice versa), as you haven't defined istPrimeZahl anywhere.
Fourth, you can change sum = sum + number to simply sum += number.
Finally, you probably want to move your System.out.print line two lines below, so that it only prints the sum after the loop has ended, not at every iteration of the loop.
(Also, you might want to change your for loop so that it starts at 100, not 10 :) )
If you want the final version, I've pasted it here:
public class Prim {
public static void main(String[] args) {
int end = 200;
int count = 0;
long sum = 0;
for (int number = 100; number<=end; number++) {
if (isPrim(number)) {
sum += number;
count++;
System.out.println(sum);
}
}
}
public static boolean isPrim(int number){
for (int i=2; i*i<=number; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
The isPrim function is missing a 'return false' after the if statement. This means that isPrim will always return true, and consequently every number will get written to the console.
The System.out.print is also within for-loop, so it will print an updated sum each time. It's unclear if this is intentional, but if you want to only get a single result then that should also be moved two lines lower.
For sum of prime numbers between 100 to 200, try this code:
public class Primzahlen {
public static void main(String[] args) {
int sum = 0;
for (int i = 100; i < 200; i++)
if (isPrim(i))
sum += i;
System.out.print(sum);
}
public static boolean isPrim(int num) {
for (int i = 2; i <= Math.sqrt(num); i++)
if (num % i == 0)
return false;
return true;
}
}
First of all let me say I am quite new to programming its been my second week since I started so if you see any bad practice or error in code please accept my apologies.
I want to print sum of first n odd numbers. But so far I can only do the sum of odd number up to the given number. kindly help.
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);
System.out.print("Please enter the number : ");
int num1 = userInput.nextInt();
int sum = sumOfOdd(num1);
System.out.println("sum of first " +num1 + " odd numbers is " + sum);
userInput.close();
}
static int sumOfOdd(int num)
{
int sum = 0;
for (int i = 0; i <= num; i++)
{
if(i % 2 != 0)
{
sum += i;
}
}
return sum;
}
}
You don't have to use a loop at all
static int sumOfOdd(int num) {
return num*num;
}
For Any Arithmetic Progression, the sum of numbers is given by,
Sn=1/2×n[2a+(n-1)×d]
Where,
Sn= Sum of n numbers
n = n numbers
a = First term of an A.P
d= Common difference in an A.P
Using above formula we can derive this quick formula to calculate sum of first n odd numbers,
Sn(odd numbers)= n²
Try this it uses a for loop that increments by two to only account for odd numbers.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the value of n: ");
int n = scanner.nextInt();
System.out.println("The sum of the first " + n + " odd numbers is: " + sumOfOddNumbers(n));
}
public static int sumOfOddNumbers(int n) {
int sum = 0;
for(int i = 1; i < n*2; i+=2) {
sum += i;
}
return sum;
}
}
Example usage:
Enter the value of n: 5
The sum of the first 5 odd numbers is: 25
Try this:
static int sumOfOdd(int num) {
int sum = 0;
for (int i = 0; i < num; i++){
sum += i*2+1;
}
return sum;
}
It sums up all odd numbers until the limit is reached.
With i*2+1 you get the next odd number. Then you add it to the sum.
Tested with System.out.println(sumOfOdd(4)); and got the expected result 16 (1+3+5+7)
Change the counter to the number of times you add an odd number to the sum value...
static int sumOfOdd(int num) {
int sum = 0;
int i = 0;
int count = 0;
do {
if(i % 2 != 0) {
sum += i;
count++;
}
i++;
} while (count < num);
return sum;
}
Or even cleaner:
static int sumOfOdd(int num) {
int sum=0;
for (int i=1;i<num*2;i+=2) {
sum=sum+i;
}
return sum;
}
You should count how many numbers have you added and in the condition to check if count of numbers you summed is less or equal than your n. Just add the counter in your for loop and set condition to: count <= num and it should work.
Every time you add a number to the sum increment the count by count++.
The code suppose to look like this:
static int sumOfOdd(int num)
{
int sum = 0;
int count = 0;
for (int i = 0, count= 0; count <= num; i++)
{
if(i % 2 != 0)
{
sum += i;
count++;
}
}
return sum;
}
I haven't checked it, but it should be correct
Since you don't know how many loop cycles are required you have to change the exit condition of the for loop.
Or you can use a while loop exploiting the same exit condition.
static int sumOfOdd(int num){
int sum = 0;
int counter = 0;
int currentNumber = 0;
while (counter<num){
if(currentNumber % 2 != 0){
sum += currentNumber;
counter++;
}
currentNumber++;
}
return sum;
}
Here is the complete code you'd be using:
public class YourClass {
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);
System.out.print("Please enter the number : ");
int num1 = userInput.nextInt();
int sum = sumOfOdd(num1);
System.out.println("sum of first " +num1 + " odd numbers is " + sum);
userInput.close();
}
static int sumOfOdd(int num)
{
int counter = 0;
for (int i = 0;; i++)
{
int sum = 0;
if(i % 2 != 0)
{
counter++;
sum += i;
}
if(counter == num) return sum;
}
}
}
Another alternative.
static int sumOfOdd(int num) {
int sum = 0;
int last = 2*num-1;
for (int i = 1; i <= last; i+=2){
sum += i;
}
return sum;
}
Obviously return num*num; is the most efficient but if you're obliged to use a loop then this method avoids a * inside the loop.
This will be a tiny (tiny) bit more efficient than:
for (int i = 0; i < num; ++i){
sum += 2*i+1;
}
import java.util.*;
class karan{
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int i = n;
int sumOddNumber = n * i;
System.out.println(n*i);
}
}
I need help on how to calculate sum of the numbers that while loop prints. I have to get numbers 1 to 100 using while loop and calculate all those together. Like 1+2+3...+98+99+100. I can get numbers but can't calculate them together. Here's my code:
public class Loops {
public static void main(String[] args) throws Exception {
int i = 1;
while (i < 101) {
System.out.print(i);
i = i + 1;
}
}
}
How do I make it only print the last sum? If I try to trick the equation it just hangs.
Use another variable instead of i which is the loop variable:
int i = 1;
int sum = 0;
while (i < 101) {
sum += i;
i++;
}
Now sum will contain the desired output. In the previous version, you didn't really loop on all values of i from 1 to 101.
First either change your sum variable or index variable
public class Loops {
public static void main(String[] args) {
int sum = 0;
int i = 1;
while (i < 101) {
sum = sum + i;
++i;
}
System.out.println(sum);
}
Your sum (i) is also your index. So each time you add to it, you're skipping numbers which you want to add to it.
public class Loops {
public static void main(String[] args) {
int sum = 0;
int i = 1;
while (i < 101) {
//System.out.print(i);
sum = sum + i;
++i;
}
System.out.println(sum);
}
Alternatively, use the Gauss sum: n(n+1)/2
So, the end sum is 100(101)/2 = 5050
Try the following. Moved the values around a bit to ensure that you add up to 100 and always show the sum.
public static void main(String[] args) throws Exception {
int i = 1;
long tot = 1;
while (i < 100) {
i += 1;
tot += i;
System.out.print("Number :" + i + " ,sum="+tot);
}
}
public class Loops {
public static void main(String[] args) throws Exception {
int i = 1;
int sum = 0;
while (i < 101) {
sum = i + 1;
}
System.out.print(sum);
}
}
this code doesn't function,
it said that lessthaAverage(int) in calculateArray cannot be applied to (), I'm a beginner so I still don't understand this coding yet, this is the question ask, Write an object oriented program that randomly generates an array of 1000 integers between 1 to 1000.
Calculate the occurrences of number more than 500 and find the average of the numbers.
Count the number which is less than the average and finally sort the numbers in descending order.
Display all your output. Please do HELP ME!!!,Thank You...
import java.util.*;
import java.io.*;
//import java.util.random;
public class CalculateArray
{
//declare attributes
private int arr[] = new int[1000];
int i;
//generates an array of 1000 integers between 1 to 1000
public void genArr()
{
Random ran = new Random();
for(i = 0; i < arr.length; i++)
{
arr[i] = ran.nextInt(1000) + 1;
}
}
//Calculate the occurences of number more than 500
public int occNumb()
{
int count;
for(i = 0; i < arr.length; i++)
{
if(arr[i] > 500)
{
count++;
}
}
return count;
}
//find the average of the numbers
public int average()
{
int sum, aver;
for(i = 0; i < arr.length; i++)
{
sum += arr[i];
}
aver = sum/1000;
return aver;
}
//Count the number which is less than the average
public int lessthanAverage(int aver)
{
int cnt;
cnt = 0;
for(i = 0; i < arr.length; i++)
{
if(arr[i] < aver)
{
cnt++;
}
}
return cnt;
}
//finally sort the numbers in descending order.
public void sort(int[] num)
{
System.out.println("Numbers in Descending Order:" );
for (int i=0; i <= num.length; i++)
for (int x=1; x <= num.length; x++)
if (num[x] > num[x+1])
{
int temp = num[x];
num[x] = num[x+1];
num[x+1] = temp;
}
}
//Display all your output
public void display()
{
int count, aver;
System.out.println(arr[i] + " ");
System.out.println("Found " + count + " values greater than 500");
System.out.println("The average of the numbers is " + aver);
System.out.println("Found " + count + " values that less than average number ");
}
public static void main(String[] args)
{
CalculateArray show = new CalculateArray();
show.genArr();
int c= show.occNumb();
show.average();
int d=show.lessthanAverage();
show.sort(arr);
show.display();
}
}
Your method lessthanAverage is expecting a int parameter. You should store the result of the average method call into a int variable and pass it to the call to lessthanAverage.
int avg = show.average();
int d=show.lessthanAverage(avg);
Your lessthaAverage() method expects an average to be passed in as a parameter, but you are not passing it in when you call it.
It seems that your method lessthanAverage needs an int as a parameter, but you are not passing it in main
public int lessthanAverage(int aver)
In main aver is not being passed:
int d=show.lessthanAverage(); // where is aver?
But if you wanted to know the average inside the method you could call your average method inside lessthanAverage:
if(arr[i] < this.average())
and not pass any parameter at all:
public int lessthanAverage()