Im trying to understund how do I find whether the number is Happy Number or not,
I know that i need to check if the unit digit and the digit in the highest number location are greater
then the numbers in the middele.
`example:
given number: 63240
the unit: 6
the number in the highest location:0
are both of them greater then 3 and 2 and4(middle) ? yes
result: true (for that case)
the quation is:
write a program that get a number from user, the program will print if the given number from the user is a happy number or not
I know how to find the units and the highest number location, but got stack figure it out how to
how to use the digits in the middle in order to find the answer for that..
notice that the only class we've learned so fat is Math,(not even string yes)
we also learned while and for but nothing so far..
I also know that in order to go through all digit in given number i need to use the while loop,
but I dont know how do I use it in order to use them to get to the answer..
my code so far:
int number;
int units;
int highestDigitLoc;
bool isHappyNumber = true;
int count = 0;
Console.WriteLine("enter a number:");
number = int.Parse(Console.ReadLine());
while(number > 0)
{
count++;
units = number % 10;
highestDigitLoc = number / 10;
}
thanks
This link explains what Happy Number's are in a simple way. Basically you have to keep suming the square of each digit present in the number, until the result equals 1. This proccess can go on indefinitely, but fortunately we know for certain that if the sum equals 4, it will never result in a Happy Number. Therefore, we can do the following:
private static bool IsHappy(int n)
{
if (n == 1)
return true;
else if (n == 0 || n == 4)
return false;
else
return IsHappy(SumDigitSquares(n));
}
private static int SumDigitSquares(int n)
{
if (n < 10)
return n * n;
else
return SumDigitSquares(n % 10) + SumDigitSquares(n / 10);
}
Usage:
bool result = IsHappy(63240); //false
Well, your question very vague, however, we can turn the number into an array of digits int[] digits
using System.Linq;
...
int[] digits = null;
while (true) {
Console.WriteLine("enter a number:");
// string : let's solve for arbitrary long numbers (no necessary int)
string number = Console.ReadLine().Trim();
if (string.IsNullOrEmpty(number))
Console.WriteLine("Empty string is not enough");
else if (number.All(c => c >= '0' && c <= '9')) {
// This code preserves leading zeroes
digits = number.Select(c => c - '0').ToArray();
// This code removes leading zeroes
//digits = number
// .SkipWhile(c => c == '0')
// .Select(c => c - '0')
// .DefaultIfEmpty()
// .ToArray();
break;
}
else
Console.Write("Not a valid integer value. Please, try again.");
}
Then we can use this int[] digits to implement any logic required.
Please, note, that we preserve leading zeroes:
"63240" -> int[] {6, 3, 4, 2, 0}
"063240" -> int[] {0, 6, 3, 4, 2, 0}
e.g.
let a number be happy if and only if
It contains at least 3 digits (in order to have middle ones)
Max of the first and last digits is greater than max of all the other digits
In our case with 63240
63240 has 5 digits, the condition holds
Max(0, 6) == 6 > Max(3, 2, 4) == 4, the condition holds
Code:
bool isHappyNumber =
digits.Length >= 3 &&
Math.Max(digits[0], digits[digits.Length - 1]) >
digits.Skip(1).Take(digits.Length - 2).Max();
Edit: let's implement isHappyNumber with good old for loops:
int maxFirstAndLast = digits[0] > digits[digits.Length - 1]
? digits[0]
: digits[digits.Length - 1];
int maxMiddle = 0;
for (int i = 1; i < digits.Length - 1; ++i)
if (digits[i] > maxMiddle) then
maxMiddle = digits[i];
bool isHappyNumber =
digits.Length >= 3 &&
maxFirstAndLast > maxMiddle;
//Remeber to add using System.Linq;
public static bool IsHappyNumber(int num)
{
var numbers = new List<int>();
while (true)
{
int sum = 0;
var digits = num.ToString().Select(x => int.Parse(x.ToString())).ToList();
foreach (var digit in digits)
sum += digit * digit;
if (numbers.Contains(sum))
break;
numbers.Add(sum);
num = sum;
}
return numbers.LastOrDefault() == 1;
}
Related
I am facing a problem while solving this task.
I should write a program which find the count of prime numbers which can be created using digits of given number, but without repetition unless digit itself repeated in given number.
For example, program should give 5 as output for number = 123. Because
{1, 2, 3, 12, 13, 21, 23, 123, 132, 213, 231, 312, 321}
has 5 prime numbers.
But if given number = 133 then program should count prime number from this list :
{1, 3, 13, 31, 33, 133, 313, 331}
Is there any way to write this program without using array? I have searched every source, but still cannot find a solution. If you have any idea, please help.
I am trying to write something like that. But it is still not working. It is not creating number as I want. One-digit numbers is a little bit closer than 3-digit when I enter 123 . Output is like that:
enter image description here
System.Console.WriteLine("Enter the number: ");
int number = Convert.ToInt32(Console.ReadLine());
int enteredNumber = number;
int length = 0;
while (number != 0)
{
length++;
number /= 10;
}
System.Console.WriteLine($"{length} length");
number = enteredNumber;
int nDigit = 1;
int count = 0;
int temp = number;
while (nDigit <= length)
{
int n = nDigit;
while (number != 0)
{
int digit = number % 10;
if (nDigit == 1 && isPrime(digit))
{
System.Console.WriteLine("1-digit prime number : " + digit);
count++;
}
else
{
int tempNewNumber = digit * Convert.ToInt32(Math.Pow(10, Convert.ToDouble(nDigit - 1)));
int newNumber = tempNewNumber;
while (temp != 0)
{
if (nDigit - 2 >= 0)
{
newNumber += (temp % 10) * Convert.ToInt32(Math.Pow(10, Convert.ToDouble(nDigit - 2)));
nDigit--;
}
if (nDigit == 1)
{
System.Console.WriteLine("in while : " + newNumber);
if (isPrime(newNumber))
{
System.Console.WriteLine("prime number : " + newNumber);
count++;
}
newNumber = tempNewNumber;
nDigit = n;
}
temp /= 10;
}
nDigit = n;
temp = enteredNumber;
}
number /= 10;
}
number = enteredNumber;
nDigit++;
}
System.Console.WriteLine("Count : " + count);
}
static bool isPrime(int num)
{
if (num <= 1) return false;
int i = 2;
while (i <= num / 2)
{
if (num % i == 0)
return false;
i++;
}
return true;
}`
You can do what you want without arrays: Identify a number by the product of the nth prime number for each digit n.
If two numbers have the same id, they are digit-wise permutations of each other.
If the id of one number p is evenly divisibly by the id of another number q, then q has fewer digits than p, but all digits of q can also found in p.
You can now test all numbers in the possible range, for example all numbers with 3 or fewer digits, whether they can be made from the given digit. This is probably not very efficient, especially for large numbers, but hey! – no arrays. (And permutations of large sets have their own performance issues.)
The example code below finds the 16 permutations of 123, but it doesn't check whether the numbers are primes.
public class Permutor
{
static uint[] prime = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};
static uint code(uint n)
{
uint res = 1;
while (n > 0) {
res *= prime[n % 10];
n /= 10;
}
return res;
}
static uint ceiling(uint n)
{
uint c = 1;
while (n > 0) {
c *= 10;
n /= 10;
}
return c;
}
static void Main(string[] args)
{
uint num = 123;
uint id = code(num);
uint max = ceiling(num);
for (uint i = 1; i < max; i++) {
if (id % code(i) == 0) {
Console.WriteLine(i);
}
}
}
}
There's room for improvement. For example, the actual ceiling for 123 is, of course, 321, so you could try to find that from the code instead of overestimating the ciling to 1000.
When you look for primes, you don't need to visit every number. Except 2 and 3, all prime numbers are either 2*k - 1 or 2*k + 1.
How can I get all n-digit numbers whose sum of digits equals to given sum? I need the fastest solution because n can be equal with 9 and sum can be equal with 1000.
I have implemented the solution below but it's too slow...
List<int> l = new List<int>();
void findNDigitNumsUtil(int n, int sum, char[] ou, int index)
{
if (index > n || sum < 0)
return;
if (index == n)
{
if (sum == 0)
{
ou[index] = '\0';
string s = new string(ou);
l.Add(Int32.Parse(s));
}
return;
}
for (int i = 0; i <= 9; i++)
{
ou[index] = (char)(i + '0');
findNDigitNumsUtil(n, sum - i, ou,
index + 1);
}
}
void findNDigitNums(int n, int sum)
{
char[] ou = new char[n + 1];
for (int i = 1; i <= 9; i++)
{
ou[0] = (char)(i + '0');
findNDigitNumsUtil(n, sum - i, ou, 1);
}
}
I need the fastest solution
No, you need a fast-enough solution. You are probably unwilling to spend even a million dollars on custom hardware to get the fastest possible solution.
How can I get all n-digit numbers whose sum of digits equals to given sum?
Here, I'll give you the solution for a slightly different problem:
What are all the sequences of n digits drawn from 0-9 that sum to sum?
This is different because this counts 01 and 10 as sequences of length two that sum to 1, but 01 is not a two-digit number.
I'll give you a hint for how to solve this easier problem. You then take that solution and adapt it to your harder problem.
First, can you solve the problem for one-digit numbers? That's pretty easy. The one-digit numbers whose digits sum to n are the digit n if n is 0 through 9, and there is no solution otherwise.
Second: Suppose n > 1. Then the n-digit numbers that sum to sum are:
0 followed by all the n-1 digit numbers that sum to sum
1 followed by all the n-1 digit numbers that sum to sum-1
2 followed by all the n-1 digit numbers that sum to sum-2
...
9 followed by all the n-1 digit numbers that sum to sum-9
Write an implementation that solves that problem, and then adapt it to solve your problem.
You can treat n-digit number as an array of n digits. Then you can increment a particular number to the next number that also adds up to the sum. Stepping through all the next answers, you have generated all possible combinations.
Using a generator to yield each n-digit combination as an IEnumerable<int> (in fact, an int[]), you start with the "smallest" n-digit combination that yields the sum, and go through each one.
IEnumerable<IEnumerable<int>> DigitsToSum(int n, int sum) {
if (sum > 9 * n)
yield return Enumerable.Empty<int>();
else {
var ans = new int[n];
void distribute(int wsum, int downto) {
for (var j1 = n - 1; j1 > downto; --j1) {
if (wsum > 9) {
ans[j1] = 9;
wsum -= 9;
}
else {
ans[j1] = wsum;
wsum = 0;
}
}
}
ans[0] = Math.Max(1, sum-9*(n-1));
distribute(sum-ans[0], 0);
bool nextAns() {
var wsum = ans[n-1];
for (var j1 = n - 2; j1 >= 0; --j1) {
wsum += ans[j1];
if (ans[j1] < Math.Min(9, wsum)) {
++ans[j1];
distribute(wsum - ans[j1], j1);
return true;
}
}
return false;
}
do {
yield return ans;
} while (nextAns());
}
}
This is tremendously faster than my recursive double generator solution (somewhat like #EricLippert's suggestion) to iterate over all possibilities (e.g. using Count()).
You can put the digits back together to get a final numeric string for each number:
var ans = DigitsToSum(n, sum).Select(p => String.Join("", p));
I try to write program that check the ratio between odd and even
digits in a given number. I've had some problems with this code:
static void Main(string[] args)
{
int countEven = 0 ;
int countOdd = 0 ;
Console.WriteLine("insert a number");
int num = int.Parse(Console.ReadLine());
int length = num.GetLength;
for (int i = 0;i<length ; i++)
{
if((num/10)%2) == 0)
int countEven++;
}
}
any ideas?
The problem is that int does not have a length, only the string representation of it has one.As an alternative to m.rogalski answer, you can treat the input as a string to get all the digits one by one. Once you have a digit, then parsing it to int and checking if it is even or odd is trivial.Would be something like this:
int countEven = 0;
int countOdd = 0;
Console.WriteLine("insert a number");
string inputString = Console.ReadLine();
for (int i = 0; i < inputString.Length; i++)
{
if ((int.Parse(inputString[i].ToString()) % 2) == 0)
countEven++;
else
countOdd++;
}
Linq approach
Console.WriteLine("insert a number");
string num = Console.ReadLine(); // check for valid number here?
int countEven = num.Select(x => x - '0').Count(x => x % 2 == 0);
int countOdd = num.Select(x => x - '0').Count(x => x % 2 != 0);
Let's assume your input is : 123456
Now all you have to do is to get the modulo from the division by ten : int m = num % 10;
After that just check if bool isEven = m % 2 == 0;
On the end you have to just divide your input number by 10 and repeat the whole process till the end of numbers.
int a = 123456, oddCounter = 0, evenCounter = 0;
do
{
int m = a % 10;
switch(m % 2)
{
case 0:
evenCounter++;
break;
default: // case 1:
oddCounter++;
break;
}
//bool isEven = m % 2 == 0;
}while( ( a /= 10 ) != 0 );
Online example
Made a small change to your code and it works perfectly
int countEven = 0;
int countOdd = 0;
Console.WriteLine( "insert a number" );
char[] nums = Console.ReadLine().ToCharArray();
for ( int i = 0; i < nums.Length; i++ )
{
if ( int.Parse( nums[i].ToString() ) % 2 == 0 )
{
countEven++;
}
else
{
countOdd++;
}
}
Console.WriteLine($"{countEven} even numbers \n{countOdd} odd numbers");
Console.ReadKey();
What I do is get each number as a a character in an array char[] and I loop through this array and check if its even or not.
If the Input number is a 32-bit integer (user pick the length of the number)
if asked:
The number of even digits in the input number
Product of odd digits in the input number
The sum of all digits of the input number
private void button1_Click(object sender, EventArgs e) {
int num = ConvertToInt32(textBox1.Text);
int len_num = textBox1.Text.Length;
int[] arn = new int[len_num];
int cEv = 0; pOd = 0; s = 0;
for (int i = len_num-1; i >= 0; i--) { // loop until integer length is got down to 1
arn[i] = broj % 10; //using the mod we put the last digit into a declared array
if (arn[i] % 2 == 0) { // then check, is current digit even or odd
cEv++; // count even digits
} else { // or odd
if (pOd == 0) pOd++; // avoid product with zero
pOd *= arn [i]; // and multiply odd digits
}
num /= 10; // we divide by 10 until it's length is get to 1(len_num-1)
s += arn [i]; // sum of all digits
}
// and at last showing it in labels...
label2.Text = "a) The even digits count is: " + Convert.ToString(cEv);
label3.Text = "b) The product of odd digits is: " + Convert.ToString(pOd);
label4.Text = "c) The sum of all digits in this number is: " + Convert.ToString(s);
}
All we need in the interface is the textbox for entering the number, the button for the tasks, and labels to show obtained results. Of course, we have the same result if we use a classic form for the for loop like for (int i = 0; and <= len_num-1; i++) - because the essence is to count the even or odd digits rather than the sequence of the digits entry into the array
static void Main(string args[]) {
WriteLine("Please enter a number...");
var num = ReadLine();
// Check if input is a number
if (!long.TryParse(num, out _)) {
WriteLine("NaN!");
return;
}
var evenChars = 0;
var oddChars = 0;
// Convert string to char array, rid of any non-numeric characters (e.g.: -)
num.ToCharArray().Where(c => char.IsDigit(c)).ToList().ForEach(c => {
byte.TryParse(c.ToString(), out var b);
if (b % 2 == 0)
evenChars++;
else
oddChars++;
});
// Continue with code
}
EDIT:
You could also do this with a helper (local) function within the method body:
static void Main(string args[]) {
WriteLine("Please enter a number...");
var num = ReadLine();
// Check if input is a number
if (!long.TryParse(num, out _)) {
WriteLine("NaN!");
return;
}
var evenChars = 0;
var oddChars = 0;
// Convert string to char array, rid of any non-numeric characters (e.g.: -)
num.ToCharArray().Where(c => char.IsDigit(c)).ToList().ForEach(c => {
byte.TryParse(c.ToString(), out var b);
if (b % 2 == 0)
evenChars++;
else
oddChars++;
// Alternative method:
IsEven(b) ? evenChars++ : oddChars++;
});
// Continue with code
bool IsEven(byte b) => b % 2 == 0;
}
Why am I using a byte?
Dealing with numbers, it is ideal to use datatypes that don't take up as much RAM.
Granted, not as much an issue nowadays with multiple 100s of gigabytes possible, however, it is something not to be neglected.
An integer takes up 32 bits (4 bytes) of RAM, whereas a byte takes up a single byte (8 bits).
Imagine you're processing 1 mio. single-digit numbers, and assigning them each to integers. You're using 4 MiB of RAM, whereas the byte would only use up 1 MiB for 1 mio. numbers.
And seeming as a single-digit number (as is used in this case) can only go up to 9 (0-9), you're wasting a potential of 28 bits of memory (2^28) - whereas a byte can only go up to 255 (0-255), you're only wasting a measly four bits (2^4) of memory.
Question: Print all the number who has unique digits only.
Input : n =15
output: 1 2 3 4 5 6 7 8 9 10 12 13 14 15
Here 11 is not included because it has 1 two times, same way 123, 456 .. are also valid but 121 1344 are not valid because there is same digit more than once.
I am running loop from 1- n and checking each number.
I am using Hash-map to determine the uniqueness of number.
Is there any better solution of above problem.
i'm not sure , but something like that..
List<int> numbers = new List<int>(){};
numbers =numbers.Where(p=>validCheck(p)==true).ToList();
static bool validCheck(int n)
{
return (n.ToString().Length==n.ToString().Disctinct().Count());
}
You could use LINQ, convert the number into a string and check if the length of the string is equal to the number of distinct charchters.
for (int i = 1; i < n; i++){
if (i.ToString().Length == i.ToString().Distinct().Count())
Console.Out.Write(i + " ");
}
as a semi useful library function where you seed it with a start and how many you want.
public static IEnumerable<int> UniqueDigits(int start, int count)
{
for (var i = start; i < (start + count); i++)
{
var s = i.ToString();
if (s.Distinct().Count() == s.Length)
{
yield return i;
}
}
}
then
UniqueDigits(0,15).ToList().ForEach(Console.WriteLine);
or
foreach (var digit in UniqueDigits(100,50))
{
Console.WriteLine(digit);
}
This is how I eliminate the numbers that have a duplicate characters.
Console.Write("Input:");
int number = int.Parse(Console.ReadLine());
List<int> numbers = new List<int>();
List<int> acceptedNumbers = new List<int>();
for (int i = 1; i <= number; i++)
{
numbers.Add(i);
}
foreach (var num in numbers)
{
bool rejected = false;
char[] numChars = num.ToString().ToCharArray();
foreach (var numChar in numChars)
{
if (numChars.Where(n => n == numChar).Count() > 1)
{
rejected = true;
}
}
if (!rejected)
{
acceptedNumbers.Add(num);
}
}
acceptedNumbers.ForEach(n => Console.Write($"{n} "));
Console.Read();
A string is an IEnumerable - so you can use a LINQ statement to solve your problem:
Numbers.Where(N => N.ToString().Distinct().Count() == N.ToString().Length);
The query is checking how many characters of the string of your number distinct and comares this number with the number of total characters.
Here is the whole code printing out all distinct numbers until 20:
List<int> Numbers = new List<int>();
for (int i = 1; i <= 20; i++)
{
Numbers.Add(i);
}
IEnumerable<int> AcceptedNumbers = Numbers.Where(N => N.ToString().Distinct().Count() == N.ToString().Length);
foreach (int AcceptedNumber in AcceptedNumbers)
{
Console.WriteLine(AcceptedNumber);
}
My thoughts:
Run the Loop from 0 to n
For each batch of 10 ( like from 0 to 9 , 10 to 19, 230 to 239..), pick the digits apart from the last one. These digits map to the counter which tends to be skipped. Rest all are to be emitted. For eg : for batch 12x , pick 1 & 2 , now we know that we have to skip numbers at position 1 and 2 , and rest all are acceptable so no need to do any processing for them.
Keep the above digits in sorted manner in an arrayList and keep a pointer at index 0. Lets call it 'ptr'. While running through that batch, check if count ( which moves from 0 to 9 ) for each batch is equal to the array[ptr]. If no, emit the number out. Else, skip it and do ptr++.
When you are doing step 2, check if any digits are duplicate. If yes, skip the entire batch of 10.
There are no string operations happening, so it should bring in the efficiency
Another solution is using integer division and modulo (no number to string conversion). You can verify the uniqueness of a number with the following method (assume digits is int array having 10 elements).
public static bool IsUnique(int num) {
int[] digits = new int[10];
num = Math.Abs(num);
while (num > 0) {
int r = num % 10;
num /= 10;
digits[r] ++;
if (digits[r] > 1) {
return false;
}
}
return true;
}
Working example http://ideone.com/9emEoz
There are only 9 * 9! / (10 - n)! unique-digit numbers with n digits. For larger n, you might want a next lexicographic algorithm to avoid unnecessary iterations. (For example, there are only 544,320 7-unique-digit numbers, yet your program would need to iterate through almost 10 million numbers to produce them!)
Here's my attempt at a next lexicographic procedure for a set of n-unique-digit numbers (where n > 1):
(1) From left to right, start with the digits 10, then ascend from 2.
For example, the first 4-digit number would be 1023.
(2) Increment the right-most digit that can be incremented to the next available
higher digit unused by digits to its left. Ascend to the right of the
incremented digit with the rest of the available digits, starting with lowest.
Examples: 1023 -> 1024 (4 is unused by the digits left of 3)
^
9786 -> 9801 (8 is unused be the digits left of 7)
^
9658 -> 9670 (7 is unused by the digits left of 5)
^
Ok, so at first, I'm very beginner in programming. It's my school homework and I cannot use conversion to string. Just if,else,for,while.
On input there is the number and the digit.
I know how to get information what number is a specified digit in a number but I have no idea how to find out how many of these numbers are there.
Let's say I have number 123 467 (it has to be less than 999 999) and I want the third number. I know it's bigger than 100 000, so I do the math - (int) 123 467 / 100 = 123 and then 123%10 = 3. Now I need to know if there are any more 3's in the number - but here is the point - I'm not sure what cycle should I use.
And I also have to create some code which determines how large is the number (bigger than 100/1000/10000/...).
I'm not asking for a full solution but little help would be appreciated. Even in a pseudolanguage.
Current code (almost nothing):
double digit, number;
try
{
digit = Convert.ToInt32(poledigit.Text);
number = Convert.ToInt32(polenumber.Text);
}
catch
{
MessageBox.Show("Zadejte číslo ve správném formátu");
return;
}
if (digit > 6 & number > 999999)
{
MessageBox.Show("Číslo musí být menší než 999 999 a digit musí být menší než 6.");
return;
}
while(number >= 100000)
{
number /= Math.Pow(10, digit);
number %= 10;
}
I would create an int array counting the number of digits
int[] digitCount = new int[10]; // Range: digitCount[0..9]
Then determine the digits one by one by eliminating the last one, until the number is zero. The loop would repeat the following code:
int digit = number % 10;
number /= 10;
digitCount[digit]++;
Now digitCount contains the count of each digit
int countOfDigit3 = digitCount[3];
If you cannot use arrays, count only the occurences of the desired digit
int digit = ...;
int digitCount = 0;
while (number != 0) {
int d = number % 10;
number /= 10;
if (d == digit) {
digitCount++;
}
}
You can iterate through the digits as follows:
int digitToSearch = 3;
int count = 0;
while (number != 0)
{
int digit = number % 10;
if (digit == digitToSearch)
count++;
number /= 10;
}