For loop confused as to which value to consider - java

I have this loop here:
while(n != 0)
{
ld = n % 10;
System.out.println(ld);
for ( i=1; i <= ld; i++)
{
f = f * i;
}
System.out.println(f);
n /= 10;
}
Let us consider a number, say 123. Now, this loop calculates the factorial of 3 accurately, but when it restarts to calculate the factorial of 2, the for loop gets confused as to which value to take for the variable ld. Is there any solution to this?

The problem is not ld. You forgot to resetf in each iteration.
while(n != 0)
{
ld = n % 10;
System.out.println(ld);
f = 1; // reset f
for ( i=1; i <= ld; i++)
{
f = f * i;
}
System.out.println(f);
n /= 10;
}
Output :
3
6 // factorial of 3
2
2 // factorial of 2
1
1 // factorial of 1

You need to reset f once you are done with one number.
Add f = 1; when you enter in while loop.
Solution
while(n != 0)
{
ld = n % 10;
f = 1;// add this
System.out.println(ld);
for (int i=1; i <= ld; i++)
{
f = f * i;
}
System.out.println(f);
n /= 10;
}

You may look in to this code,code is ok just need to set the value for f inside the loop for each digit for given number.
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
int ld;
int n=123;
while(n != 0)
{
int f=1;
ld = n % 10;
System.out.println(ld);
for ( int i=1; i <= ld; i++)
{
f = f * i;
}
System.out.println(f);
n /= 10;
}
}
}
output are as
3
6
2
2
1
1

Most important:
Now our loop resets f to 1 every "repeat".
Additional:
Added int i = 1 to for loop.
You can use f *= 1; instead of f = f * 1;
Changed n != 0 to n > 0 for more safety .
while(n > 0)
{
ld = n % 10;
System.out.println(ld);
f = 1;
for(int i = 1; i <= ld; i++)
{
f *= i;
}
System.out.println(f);
n /= 10;
}

Related

Avoid using BigInteger

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;
}

Finding all the factors of a number in Java?

"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();
}
}

Prime number generator between 2 nums

I cant figure out which test cases the code provided below fails.
problem:
All submissions for this problem are available.
Shridhar 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 first line contains t, the number of test cases (less then or equal to 10).
Followed by t lines which contain 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. Separate the answers for each test case by an empty line.
Example
Input:
2
1 10
3 5
Output:
2
3
5
7
3
5
import java.util.Scanner;
public class Main implements Runnable {
public static void main(String args[]) {
new Main().run();
}
#Override
public void run() {
Scanner sc = new Scanner(System.in);
Integer d;
try {
d = sc.nextInt();
boolean isPrime[] = new boolean[100000];
for (int i = 0; i < d; i++) {
int m = sc.nextInt();
int n = sc.nextInt();
if (n <= 0 || m > n) {
continue;
}
if (m <= 0) {
m = 2;
if (m > n) {
continue;
}
}
if (m == 1) {
m = 2;
}
if (m == 2 && n - m == 0) {
System.out.println(2);
} else {
for (int k = 0; k <= n - m; k++) {
isPrime[k] = true;
}
int sqrt = (int) Math.sqrt(n);
for (int j = 2; j <= sqrt; j++) {
int k = (m % j == 0) ? m / j : (m + j) / j;
for (; k <= n / j; k++) {
if (!(m == 2 && (j * k == 2)) && k != 1) {
isPrime[j * k - m] = false;
}
}
}
for (int a = m; a <= n; a++) {
if (isPrime[a - m]) {
System.out.println(a);
}
}
}
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
sc.close();
}
}
}
Your problem is with this:
boolean isPrime[] = new boolean[100000];
and this:
for (int k = 0; k <= n - m; k++) {
isPrime[k] = true;
}
because some time n - m = 100000 then you need isPrime[100000] which you didnt allocate so you need to declare isPrime like this:
boolean isPrime[] = new boolean[100001];

Armstrong number code in Java is not working right

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);
}
}
}
}

Debugging for loop in palindrome numbers code

This code gets an integer n and displays all palindrome numbers less than n.
But seems the for loop doesn't work; because when I enter a number except 0, 1 and negatives, nothing happens.
I tried debugging, but couldn't find the problem!
Sample input: 30
Sample output: 1 2 3 4 5 6 7 8 9 11 22
import java.util.Scanner;
public class PalindromeNumbers {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
if (n == 0 || n == 1 || n < 0)
System.out.println("There's no Palindrome Number!");
else {
for (int num = 1; num < n; num++) {
int reversedNum = 0;
int temp = 0;
while (num > 0) {
// use modulus operator to strip off the last digit
temp = num % 10;
// create the reversed number
reversedNum = reversedNum * 10 + temp;
num = num / 10;
}
if (reversedNum == num)
System.out.println(num);
}
}
}
}
You run into an infinite loop: you use num in your for loop as an index, and reset it to 0 inside the loop. Use different variables, and it should work!
for (int i = 1; i < n; i++) {
int num = i;
...
if (reversedNum == i)
System.out.println(i);
}
You can do it in a more concise way:
public static void main(final String args[]) {
final Scanner input = new Scanner(System.in);
final int max = input.nextInt();
if (max <= 0) {
System.out.println("There's no Palindrome Number!");
} else {
for (int i = 1; i < max; i++) {
if (isPalindrome(i)) {
System.out.println(i);
}
}
}
}
private static boolean isPalindrome(final int num) {
final String temp = "" + num;
return new StringBuilder(temp).reverse().toString().equals(temp);
}
You are changing your num variable inside your for loop. The next time num < n is executed, the value changed (to 0). Try something like this:
for (int num = 1; num < n; num++) {
int reversedNum = 0;
int temp = 0;
int temp2 = num;
while (temp2 > 0) {
// use modulus operator to strip off the last digit
temp = temp2 % 10;
// create the reversed number
reversedNum = reversedNum * 10 + temp;
temp2 = temp2 / 10;
}
if (reversedNum == num)
System.out.println(num);
}
This way, you use a temp variable to calculate your reversedNum, and still keeps the value of num for the next loop iteration.

Categories