im need to calculate the sum of n terms i wrote this code but it print me all the nums but no the sum
for (i = 1; i <= n; i++){
for ( j = 0; j < i; j++){
System.out.print(i);
}
}
And this is what it print
122333444455555
Thanks for your help
If by 'sum of N terms' you mean,
N=4
Sum= 1+2+2+ 3+3+3+4+4+4+4....N*N
Then it's safe to say that it's Sum(i*i) where 0<i<=N,
this solution will give you answer:
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i * i;
}
System.out.println(sum);
One good approach here is make use of the modulus:
int input = 122333;
int sum = 0;
while (input > 0) {
sum += input % 10;
input /= 10;
}
System.out.println("Sum of all terms is: " + sum); // 14
The input % 10 term will return the final rightmost digit in the input. We added this to the running total, and then divide the input by 10 to advance the next digit.
I finally did it
for (i = 1; i <= n; i++){
for ( j = 0; j < i; j++){
res=res+i;
System.out.print(i);
}
}
System.out.println(" La sumatoria es "+res);
Related
How can I print this using for loops?
1
22
333
4444
55555
I have tried this. But it is not printing what I want to print.
public class void main(String[] args) {
int last = 5, first = 1;
for (int i = 1; i <= last; i++) {
for (int j = last; j > i; j++) {
System.out.print(" ");
}
for (int k = i; k >= 1; k--){
System.out.print(k);
}
System.out.println();
}
}
It just prints this.
1
21
321
4321
54321
As you can see the first time you print, it is correct, then is when k is equal to i, so just print i
System.out.print(i);
edit
As per your edited code, do my above change, plsu
for (int j = last; j > i; j--) {
output
1
22
333
4444
55555
final
int last = 5;
for (int i = 1; i <= last; i++) {
for (int j = last; j > i; j--) {
System.out.print(" ");
}
for (int k = i; k >= 1; k--){
System.out.print(i);
}
System.out.println();
}
Your new problem solution just change k into i System.out.print(i)
int last = 5, first = 1;
for (int i = 1; i <= last; i++) {
for (int j = last; j > i; j--) {
System.out.print(" ");
}
for (int k = i; k >= 1; k--){
System.out.print(i);
}
System.out.println();
}
Output:
1
22
333
4444
55555
To get working code, it's helpful to first describe the detailed solution in words. That might be:
To print a triangle of height height, individually print each row from 1 to n.
To print a single row row, determine:
How many spaces it needs.
How many digits it needs.
Which digit to print.
The digit to print is the same as the row number row.
The number of digits digits is also the same as the row number row.
The number of spaces spaces depends on how long the line should be in total.
The number of spaces is width - digits.
To print a character repeatedly, use a for loop counting from 0 up to but excluding the repetition.
This description then translates into this code:
public static void main(String[] args) {
int height = 5;
int width = height; // can also be larger than height
for (int row = 1; row <= height; row++) {
int digit = row;
int digits = row;
int spaces = width - digits;
for (int i = 0; i < spaces; i++) {
System.out.print(' ');
}
for (int i = 0; i < digits; i++) {
System.out.print(digit); // assuming that digit needs only a single character to print
}
System.out.println();
}
}
Sure, this program is longer than the other ones, but when stepping through it using a debugger, you have all the information about the current state captured in the variables. By looking at the variable values, you can always ask yourself: does it make sense, and do spaces and digits and width fit together?
This program also splits up the total work into two phases. In the first phase, determine what to print and how much, and then just print it.
In every loop the number of blanks before a given number i are maxNumber - i and the times the current number is displayed are i:
for (int i = 1; i <= 5; i++)
{
String blanks = "";
for (int j = 1; j <= 5-i; j++)
{
blanks += " ";
}
String number = "";
for(int k = 1; k <= i; k++)
{
number += i;
}
System.out.print(blanks + number);
System.out.println();
}
I was wondering if there is a complexity and time difference when doing these two operations:
1)
int sum = 0;
for (int i = 0; i < 1000000; i++) {
sum = sum + i;
}
2)
int sum = 0;
for (int i = 0; i < 1000000; i++) {
sum += i;
}
or maybe image the problem to be bigger numbers/data, this is just an example.
These variants are the same from performance point of view (both will be as iadd instruction in java bytecode)
But sum += 1 replaced with sum = (int) (sum + 1)
And it has differrens for types like byte or short for compilation
E.g. this code will be compiled
byte i = 0;
for(int j = 0; j < 10; j++) {
i += j; //i = (byte) (i + j)
}
but you will get compilation error for code
byte i = 0;
for(int j = 0; j < 10; j++) {
i = i + j;
}
There is a difference in priority, compound assignment sum += i is less primary than assignment and addition sum = i + 1.
Incrementation i++ is even more primary.
for more information : operator precedence
I'm doing this program: Given an integer, n, if the sum of its divisors (not counting itself) equals n, that number is said to be perfect. If the sum is lower, it is said to be decient, and if it is higher it is said to be abundant. For example:
6 has divisors 1,2,3: they add 6, therefore 6 is perfect. 8 has divisors 1,2,4: they add 7, therefore 8 is deciente. 24 has divisors 1,2,3,4,6,8,12: they add 36, therefore 24 is abundant.
Write a program that reads two positive integers and displays, on the screen, how many numbers there are of each type in that interval (including the extremes).
I have the following code and I know where it fails, for example if I enter a single number, I do it well, example of entries 6 and 7. If I then enter 6 and 9 the output is Perfect 1 Deficient 0 Abundant 2, when I should to be Perfect 1 Deficient 2 Abundant 0. Variable j stores the divisors of all in the variable j and then that's why it's abundant but I have not been able to correct it for more than I've tried.
import java.util.Scanner;
public class PerfectNumbers {
public static void main(String[] args) {
System.out.println("Enter two numbers for the interval:");
Scanner teclado = new Scanner(System.in);
int x = teclado.nextInt();
int y = teclado.nextInt();
int cont1 = 0;
int perfect = 0;
int deficient = 0;
int abundant = 0;
for (int i = x; i < y; i++) {
for (int j = 1; j < i; j++) {
if (i % j == 0) {
cont1 += j;
} else {
cont1 += 0;
}
}
if (cont1 == x) {
perfect += 1;
} else if (cont1 < x) {
deficient += 1;
} else if (cont1 > x) {
abundant += 1;
}
}
System.out.println("Perfect"+ perfect);
System.out.println("Deficient"+ deficient);
System.out.println("Abundant"+ abundant);
}
}
One problem is that you didn't reset cont1.
Another problem is that instead of comparing to x to decide perfect/deficient/abundant, you need to compare to i.
for (int i = x; i < y; i++) {
cont1 = 0;
for (int j = 1; j < i; j++) {
if (i % j == 0) {
cont1 += j;
}
}
if (cont1 == i) {
perfect += 1;
} else if (cont1 < i) {
deficient += 1;
} else {
abundant += 1;
}
}
I think the second problem was easy to overlook because of the poor naming of variables. I suggest to improve that, and it will be easier to read and harder to make such mistakes:
for (int n = start; n < end; n++) {
sum = 0;
for (int j = 1; j < n; j++) {
if (n % j == 0) {
sum += j;
}
}
if (sum == n) {
perfect++;
} else if (sum < n) {
deficient++;
} else {
abundant++;
}
}
I am supposed to create a perfect number class using the following pseudocode:
For i from 2 to “very large”,
For j from 2 to √i,
if (j evenly divides i),
accumulate the sum j and i/j
if √i is an integer
subtract √i ... you added it twice
if the sum of divisors == i
Print the number ... it’s perfect!
So here is my version. It runs, but it doesn't do what I want at all. It just runs and produces nothing as an output. Can someone tell me what is wrong with my program? It's bothering me so much.
import java.util.Scanner;
public class PerfectNumber {
public static void main(String[] args) {
double sum = 0
double newsum = 0;
for (int i = 2; i < 1000000; i++) {
for (int j = 2; i<Math.sqrt(i); j++){
if (i%j==0){
sum = j + (i%j);
}
if (Math.sqrt(i)==(int)i){
newsum = sum - Math.sqrt(i);
}
if (sum == 0) {
System.out.println(sum + "is a perfect number");
}
}
}
}
}
Few mistakes according to the algorithm:
sum = j + (i%j); should be changed to sum = j + (i/j);
This piece:
if (Math.sqrt(i)==(int)i){
newsum = sum - Math.sqrt(i);
}
if (sum == 0) {
System.out.println(sum + "is a prime number");
}
Should be under upper "for"
Math.sqrt(i)==(int)i would never be true unless i is 1. If you want to check this that way you should write Math.sqrt(i)==((int) Math.sqrt(i))
There are much more errors, the simplest way to do it is:
double sum = 0;
for (int i = 1; i <= 10000; i++) {
for (int j = 1; j < i; j++) {
if (i % j == 0) {
sum += j;
}
}
if (i == sum) {
System.out.println(sum + " is a prime number");
}
sum = 0;
}
Your code contains several mistakes. Here is the corrected code, commented with the changes.
// newsum isn't needed; declare sum to be int to avoid floating-point errors
int sum = 0;
for (int i = 2; i < 1000000; i++) {
// Start with 1; every natural number has 1 as a factor.
sum = 1;
// Test if j, not i, is less than the square root of i.
for (int j = 2; j <= Math.sqrt(i); j++){
if (i % j == 0){
// Add to sum; don't replace sum. Use i / j instead of i % j.
sum = sum + j + (i / j);
// Move test inside this if; test if j is square root of i
if (j*j == i){
// I used j because we know it's the square root already.
sum = sum - j;
}
}
// Move print outside of inner for loop to prevent multiple
// printings of a number.
// Test if sum equals the number being tested, not 0.
if (sum == i) {
// Space before is
System.out.println(sum + " is a perfect number");
}
}
}
Output:
6 is a perfect number
28 is a perfect number
496 is a perfect number
8128 is a perfect number
public static void main(String[] args){
int min = 2;
int max = 1000000;
int sum = 0;
for (; min <= max; min++,sum = 0) {
for (int e = 1; e < min; e++)
sum += ((min % e) == 0) ? e : 0;
if (sum == min){
System.out.println(sum);
}
}
}
for(n=1;n<=number;n++){ //calculates the sum of the number.
int i=1;
int sum = 0;
while(i<n){
if(n%i==0)
sum+=i;
i++;
}
if(sum==n){ //if the sum is equal to its sum :
System.out.print(n+": ");
for (int j = 1;j<n;j++){
if(n%j==0){
System.out.print(j+" ");
}
}
System.out.println();
}
}
Here is the simplest and easiest form you can write a program for perfect number....this code gives perfect number within 25 ...you can change as you want
import java.util.Scanner;
public class PerfectNumber {
public static void main(String[] args) {
int n,i,j,count=0;
for(i=2;i<=25;i++) {
for(j=1;j<=i;j++) {
if(i%j ==0) /*count increments if a reminder zero*/ {
count++;
}
}
/*since a perfect number is divided only by 1 and itself
if the count is 2 then its a prime number...*/
if(count==2)
System.out.println(i);
count=0;
}
return 0;
}
}
According to the pseudocode you want to move the second and third if test outside of the inner loop
for (int i = 2; i < 1000000; i++) {
double iroot = Math.sqrt(i);
int sum = 1;
for (int j = 2; j <= iroot; j++){
if (i % j == 0){
sum = sum + j + i / j;
}
}
if (iroot == (int) iroot) {
sum = sum - iroot;
}
if (sum == i) {
System.out.println(sum + "is a perfect number");
}
}
Thanks for watched
public boolean testPerfect(int n){
int i=1;
int sum=0;
while(i<n){
if(n%i==0)
{
sum+=i++;
}
else{
i++;}
}
if (sum==n){
return true;
}
return false;
}
I tried it several times but still gives me ArrayOutOfIndex. But i want to save the memory so i use
boolean[]isPrime = new boolean [N/2+1];
instead of
boolean[]isPrime = new boolean [N+1];
This gives me ArrayOutOfIndex for line 23 and 47
line 23:
for (int i = 3; i <= N; i=i+2) {
isPrime[i] = true;
}
line 47:
for (int i = 3; i <= N; i=i+2) {
if (isPrime[i]) primes++;
...
}
Full code:
public class PrimeSieve {
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage: java PrimeSieve N [-s(ilent)]");
System.exit(0);
}
int N = Integer.parseInt(args[0]);
// initially assume all odd integers are prime
boolean[]isPrime = new boolean [N/2+1];
isPrime[2] = true;
for (int i = 3; i <= N; i=i+2) {
isPrime[i] = true;
}
int tripCount = 0;
// mark non-primes <= N using Sieve of Eratosthenes
for (int i = 3; i * i <= N; i=i+2) {
// if i is prime, then mark multiples of i as nonprime
if (isPrime[i]) {
int j = i * i;
while (j <= N){
tripCount++;
isPrime[j] = false;
j = j + 2*i;
}
}
}
System.out.println("Number of times in the inner loop: " + tripCount);
// count and display primes
int primes = 0;
if(N >= 2 ){
primes = 1;
}
for (int i = 3; i <= N; i=i+2) {
if (isPrime[i]) primes++;
if (args.length == 2 && args[1].equals("-s"))
; // do nothing
else
System.out.print(i + " ");
}
System.out.println("The number of primes <= " + N + " is " + primes);
}
}
You should store and access the array using the same indexing function: isPrime[i/2]
When you change the size of your array from [N+1] to [N/2+1], you need to also update the end-conditions of your for-loops. Right now your for-loops run until i=N, so you are trying to do isPrime[i] when i > (N/2+1) ... so you get an ArrayIndexOutOfBoundsException.
Change this:
for (int i = 3; i <= N; i=i+2)
to this:
for (int i = 3; i <= N/2; i=i+2)
Well, for example if N=50 your isPrime only holds 26 elements, and you're trying to access the elements at 3,5..47,49 (which, of course, is out of bounds)
What you probably want is to use i/2 (as the index) inside your loops, that way you are still iterating over the numbers 3,5..47,49, but you use the correct indexes of your vector.