How to sum all whole numbers to 1000
package proba;
public class Proba {
public static void main(String[] args) {
int a = 1;
int whole = 0;
int n = 1000;
int m = 500;
while (a <= n) {
if (a % 2 == 0) {
whole += ;
}
a++;
System.out.println("Rezultat parnih je: " + whole);
}
}
}
For all numbers from 0 till 1000, for loop
int sum = 0;
for (int i = 0; i < 1000; i++) {
sum += i;
}
System.out.println(sum);
For all even numbers, use an if to see if they are even
if (i % 2 == 0) // remainder is 0, meaning even
sum += i;
Edit: To add even and subtract odd
int sumOfEven;
for (int i = 0; i < 1000; i++) {
if (i % 2 == 0) {
sumOfEven += i;
}
}
int sumOfOdd;
for (int i = 0; i < 500; i++) {
if (i % 2 != 0) {
sumOfOdd += i;
}
}
System.out.println(sumOfEven - sumOfOdd); // Math.absolute can also be done here for a non-negative value
Adding all numbers just to subtract later 250 of them is not efficient. Just filter the ones you don't want in the total sum
int sum = IntStream.rangeClosed(1, 1000)
.filter(i -> i >= 500 || i % 2 == 0)
.sum();
System.out.println(sum);
Related
calculatePiInnitial(4)
public static double calculatePiInnitial(int i){
double sum = 0;
for (int n=0; n<=i;n++){
for(int k = 1; k<=i;k =+ 2) {
if (n % 2 == 0)
sum += 1/k*Math.pow(3, n);
else
sum += -1/k* Math.pow(3, n);
}
}
Like here I want the second for loop to iterate only one time for every iteration.
So the result can be like this
1 - 1/9 + 1/135 - 1/184 .....
What if you add a break statement at the very end of the second for loop?
calculatePiInnitial(4)
public static double calculatePiInnitial(int i){
double sum = 0;
for (int n=0; n<=i;n++){
for(int k = 1; k<=i;k =+ 2) {
if (n % 2 == 0)
sum += 1/k*Math.pow(3, n);
else
sum += -1/k* Math.pow(3, n);
break;
}
}
Or you can also do this...
Only iterate until K = 2, and increment K by 1 after each iteration
calculatePiInnitial(4)
public static double calculatePiInnitial(int i){
double sum = 0;
for (int n=0; n<=i;n++){
for(int k = 1; k<=2;k ++) {
if (n % 2 == 0)
sum += 1/k*Math.pow(3, n);
else
sum += -1/k* Math.pow(3, n);
}
}
I have this question I am trying to solve
I wrote this code
public static int[] encodeNumber(int n) {
int count = 0, base = n, mul = 1;
for (int i = 2; i < n; i++) {
if(n % i == 0 && isPrime(i)) {
mul *= i;
count++;
if(mul == n) {
break;
}
n /= i;
}
}
System.out.println("count is " + count);
int[] x = new int[count];
int j = 0;
for (int i = 2; i < base; i++) {
if(n % i == 0 && isPrime(i)) {
mul *= i;
x[j] = i;
j++;
if(mul == n) break;
n /= i;
}
break;
}
return x;
}
public static boolean isPrime(int n) {
if(n < 2) return false;
for (int i = 2; i < n; i++) {
if(n % i == 0) return false;
}
return true;
}
I am trying to get the number of its prime factors in a count variable and create an array with the count and then populate the array with its prime factors in the second loop.
count is 3
[2, 0, 0]
with an input of 6936. The desired output is an array containing all its prime factors {2, 2, 2, 3, 17, 17}.
Your count is wrong, because you count multiple factors like 2 and 17 of 6936 only once.
I would recommend doing it similar to the following way, recursively:
(this code is untested)
void encodeNumberRecursive(int remainder, int factor, int currentIndex, Vector<Integer> results) {
if(remainder<2) {
return;
}
if(remainder % factor == 0) {
results.push(factor);
remainder /= factor;
currentIndex += 1;
encodeNumberRecursive(remainder , factor, currentIndex, results);
} else {
do {
factor += 1;
} while(factor<remainder && !isPrime(factor));
if(factor<=remainder) {
encodeNumberRecursive(remainder , factor, currentIndex, results);
}
}
}
Finally, call it with
Vector<Integer> results = new Vector<Integer>();
encodeNumberRecursive(n, 2, 0, results);
You can also do it without recursion, I just feel it is easier.
Well here is a piece of code I would start with. It is not finished yet and I did not test it, but that's the way you should go basically.
// First find the number of prime factors
int factorsCount = 0;
int originalN = n;
while (n > 1) {
int p = findLowestPrimeFactor(n);
n /= p;
factorsCount++;
}
// Now create the Array of the appropriate size
int[] factors = new int[factorsCount];
// Finally do the iteration from the first step again, but now filling the array.
n = originalN;
int k = 0;
while (n > 1) {
int p = findLowestPrimeFactor(n);
factors[k] = p;
k++;
n = n / p;
}
return factors;
Having found a factor (on increasing candidates), you can assume it is prime,
if you divide out the factor till the candidate no longer is a factor.
Your problem is not repeatedly dividing by the factor.
public static int[] encodeNumber(int n) {
if (n <= 1) {
return null;
}
List<Integer> factors = new ArrayList<>();
for (int i = 2; n != 1; i += 1 + (i&1)) {
while (n % i == 0) { // i is automatically prime, as lower primes done.
factors.add(i);
n /= i;
}
}
return factors.stream().mapToInt(Integer::intValue).toArray();
}
Without data structures, taking twice the time:
public static int[] encodeNumber(int n) {
if (n <= 1) {
return null;
}
// Count factors, not storing them:
int factorCount = 0;
int originalN = n;
for (int i = 2; n != 1; i += 1 + (i&1)) {
while (n % i == 0) {
++factorCount;
n /= i;
}
}
// Fill factors:
n = originalN;
int[] factors = new int[factorCount];
factorCount = 0;
for (int i = 2; n != 1; i += 1 + (i&1)) {
while (n % i == 0) {
factors[factorCount++] = i;
n /= i;
}
}
return factors;
}
I have this problem:
f(N) is the last five digits before the trailing zeroes in N!.
ex: 11! = 39916800, f(11) = 99168
ex: 13! = 6227020800, f(13) = 70208
Find f(N) where N is your function input.
And my Solution is:
public static String Solving(int n) {
if (n > 10) {
String val;
BigInteger z = BigInteger.ONE;
for (int i = 1; i <= n; i++) {
z = z.multiply(BigInteger.valueOf(i));
}
val = String.valueOf(z);
val = val.substring(n % 10);
val = val.substring(0, 5);
return val;
} else return "";
}
How I can avoid use BigInteger?
Edit: thanks user58697 and greybeard for excellent suggestion.
First, calculate the number of factor five in all numbers from 1 -> n,
Then remove all pair of 2 and 5,
Finally, calculate the result modulus 10^5.
static long mod = 100000;
public static long Solving(int n) {
int five = 0;
for (int power5 = 5, count ; 0 < (count = n / power5) ; power5 *= 5){
five += count;
}
// Number of pair (2,5) is the min number between 2 and 5
int removeFactorTwo = five;
int removeFactorFive = five;
long result = 1;
for(int i = 2; i <= n; i++){
int st = i;
while(st % 2 == 0 && removeFactorTwo > 0){
st /= 2;
removeFactorTwo--;
}
while(st % 5 == 0 && removeFactorFive > 0){
st /= 5;
removeFactorFive--;
}
result *= st;
// This will make sure result always <= 10^5
result %= mod;
}
return result;
}
"Write a program that reads an integer I and displays all its smallest factors in increasing order. For example, if the input integer is 120, the output should be as follows: 2, 2, 2, 3, 5.". At the beginning of the program, the user has to enter an integer identifying how many numbers will be factorized.
import java.util.Scanner;
public class Main {
public static void main(String [] args){
Scanner input = new Scanner(System.in);
int size = input.nextInt();
for(int i = 0; i < size; i++){
int a = input.nextInt();
for(int j = 0; j < a; j++){
if(a%j==0){
System.out.println(j);
}
}
}
input.close();
}
}
A Better way of finding all the factors is to find the factors till it's square root.
int n = 120;
for(int i = 2; i * i <= n; ++i)//check below it's square root i <= sqrt(n)
if(n % i == 0){
while(n % i == 0)
{
System.out.println(i);
n /= i;
}
}
A much more effective way is to do it with primes.
There cannot be any other prime factor which is even other than 2 so we can skip the even part
int n = 120;
if(n % 2 == 0)
{
while(n % 2 == 0)
{
System.out.println("2");
n /= 2;
}
}
for(int i = 3; i * i <= n; i += 2)//odd numbers only
{
while(n % i == 0)
{
n /= i;
System.out.println(i);
}
}
A much more efficient way is to use 6*k +- 1 rule,
What is 6*k +- 1 rule?
All prime numbers(except 2 and 3) can be represented by the above formula. Though the reverse might not be true,
Consider 6*6 - 1 = 35 divisible by 5.
If it is not a prime, it will have a prime factor less than it's square root.
So we check only for the numbers which follow the above rule.
int i = 1, n = 120;
//check for 2 and 3
if(n % 2 == 0)
{
while(n % 2 == 0)
{
System.out.println("2");
n /= 2;
}
}
if(n % 3 == 0)
{
while(n % 3 == 0)
{
System.out.println("3");
n /= 3;
}
}
while(true)
{
int p = 6 * i - 1;
if(p * p > n)
break;
if(n % p == 0)
{
while( n % p == 0)
{
n /= i;
System.out.println(p);
}
}
p = 6 * k + 1;
if(p * p > n)
break;
if(n % p == 0)
{
while( n % p == 0)
{
n /= i;
System.out.println(p);
}
}
}
If the numbers are very huge and there are alot of them, Pre-calculate primes can be helpful
I use Sieve to calculate the primes.
int max = 10000007;
boolean[]primes = new boolean[max];
int []nums = new int[max];
int numOfPrimes = 0;
for(int i = 2; i * i < max; ++i)
if(!primes[i])
for(int j = i * i; j < max; j += i)//sieve
primes[j] = true;
for(int i = 2; i < max; ++i)
if(!primes[i])
nums[numOfPrimes++] = i;//we have all the primes now.
int n = 120;
for(int i = 0; i < numOfPrimes; ++i)
{
int p = nums[i];
if(p * p > n)
break;
if(n % p == 0)
{
while(n % p == 0)
{
n /= p;
System.out.println(p);
}
}
}
You should divide the number:
for(int j = 2; j < a; j++){ // start dividing from 2
if(a%j==0){
System.out.println(j);
a/=j; // divide a with j (there is remainder 0 because of condition)
j--; // do j once more
}
}
Try this one:
package bölüm05;
import java.util.Scanner;
public class B05S16 {
public static void main(String[] args) {
Scanner java = new Scanner(System.in);
System.out.println("Bir tamsayı giriniz");
int sayı = java.nextInt();
int i = 2;
while (sayı > 1) {
if (sayı % i == 0) {
sayı = sayı / i;
System.out.print(i + ",");
} else {
i++;
}
}
java.close();
}
}
I am completely new to Java and am writing code to check whether a number is an Armstrong number or not in the range 0 to 999.
Please tell me what is wrong. When run on command prompt, it repeatedly prints:
1 is the count
Code:
import java.util.*;
class Armstrong
{
public static void main (String[] args)
{
int sum = 0;
for (int i = 0; i < 1000; i++)
{
int n = i;
int count =0;
while(n > 0)
{
int mod = n % 10;
n = n / 10;
count++;
}
System.out.println(+count+ "is the count");
for (int j = 1; j < count; j++)
{
int val = i % 10;
i= i / 10;
sum = val * val * val + sum;
}
if (sum == i)
{
System.out.println( +i+ "is an Armstrong number");
}
}
}
}
An Armstrong number is a number that is the sum of its own digits each raised to the power of the number of digits.
For starters, you always raise the digits to the power of 3, so your calculation can only work for i between 100 and 999.
Second, you are changing i within your inner loop, so the comparison at the end if (sum==i) will fail, since sum should be compared to the original i.
Next, you don't reset sum to 0 in each iteration of i.
You also skip one of the digits.
This seems to work :
int sum = 0;
for (int i = 100; i < 1000; i++) { // start at 100
sum = 0; // clear the sum in each iteration
int n = i;
int count = 0;
while (n > 0) {
int mod = n % 10;
n = n / 10;
count++;
}
n = i;
for (int j = 0; j < count; j++) { // iterate over all the digits
int val = n % 10;
n = n / 10; // don't change i
sum = val * val * val + sum;
}
if (sum == i) {
System.out.println(i + " is an Armstrong number");
}
}
This returns :
153 is an Armstrong number
370 is an Armstrong number
371 is an Armstrong number
407 is an Armstrong number
There is no need to run three loops. You can do it simpler that way:
for(int i = 0; i < 1000; i++) {
int currNumber = i;
int sum = 0;
while(currNumber != 0)
{
int mod = currNumber % 10;
sum = sum + mod * mod * mod;
currNumber = currNumber / 10;
}
if (i == sum) {
System.out.println(i + " is an Armstrong number");
}
}
Print Armstrong number in java
public class CalculatArmstrong
{
public static void main(String[] args)
{
for(int i=0;i<=2000;i++)
{
int number=i;
int n=number;
int rem;
int arms=0;
while(number>0)
{
rem=number%10;
arms=arms+rem*rem*rem;
number=number/10;
}
if(n==arms)
{
System.out.println(n);
}
}
}
}